1

現在、送信とキャンセルのボタンが付いたフォームがあります。一部のロジックによっては、ページが読み込まれるたびに、同じキャンセルボタンをアプリケーション内の他の別のページにリダイレクトする必要があります。これは、現在aspxビューにあるコードで、プロパティに基づいてlocation.hrefを変更します。

   <% if (Model.MyProperty.Equals("something"))
      { %>
       <input class="btnCancel" type="button" value="" onclick="location.href='<%: Url.Action("MyAction","MyController", new {Area="MyArea"},null)%>'" />
   <% } %>
   <% else if (Model.MyProperty.Equals("somethingelse"))
      { %>
       <input class="btnCancel" type="button" value="" onclick="location.href='<%: Url.Action("MyOtherAction","MyOtherController", new {Area="SomeOtherArea"},null)%>'" />
   <% } %>

これはこれを行うための正しくてエレガントな方法ですか?それを行う方法があれば、私はむしろ複数のIF-ELSE条件を減らしたいと思います。

御時間ありがとうございます。

4

3 に答える 3

1

プロパティをパラメーターとして取り、コントローラー内で適切にリダイレクトするキャンセル メソッドを作成できます。とにかく、ビューにはほとんどロジックがないはずなので、このロジックはおそらくあなたのビューにあるべきではありません

于 2012-05-02T15:40:15.120 に答える
0

ビュー モデルでキャンセル アクションを決定するために使用されるプロパティを (既にあるように)、他の必要なプロパティと一緒に配置します。

例えば:

public class IndexModel
{
    //any other properties you need to define here
    public string MyProperty { get; set; }
}

次に、ビューは次のようになります。

@model IndexModel

@using (Html.BeginForm())
{
    //other information you may want to submit would go here and in the model.

    @Html.HiddenFor(m => m.MyProperty)
    <button type="submit" name="submit" value="submit">submit</button>
    <button type="submit" name="cancel" value="cancel">cancel</button>
}

最後に、post アクションによって、返される次のアクションが決定されます。

[HttpPost]
public ActionResult Index(IndexModel model)
{
    if (!string.IsNullOrEmpty(Request["submit"]))
    {
        if (ModelState.IsValid)
        {
            //any processing of the model here
            return RedirectToAction("TheNextAction");
        }
        return View();
    }

    if (model.MyProperty.Equals("something"))
    {
        return RedirectToAction("MyAction", "MyController", new { area = "MyArea" });
    }
    else //assumes the only other option is "somethingelse"
    {
        return RedirectToAction("MyOtherAction", "MyOtherController", new { area = "SomeOtherArea" });
    }
}
于 2012-05-02T18:43:37.677 に答える