具有多个重定向选项的Asp.net MVC取消按钮

use*_*358 1 asp.net asp.net-mvc asp.net-mvc-3

我目前有一个带有提交和取消按钮的表单.根据某些逻辑,每次页面加载时,我都希望相同的取消按钮重定向到应用程序中的其他不同页面.这是我在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)%>'" />
   <% } %>
Run Code Online (Sandbox Code Playgroud)

这是正确而优雅的方式吗?如果有办法,我宁愿减少多个IF-ELSE条件.

谢谢你的时间.

mcc*_*002 5

我总是处理多个重定向选项的方法是在控制器操作中设置href值.

视图是通用的,但控制器操作特定于渲染页面的上下文.因此,在您的模型中,创建一个名为CancelUrl的属性.现在,在控制器操作中,将其设置为您希望它转到的链接.

model.CancelUrl = Url.Action("action", "controller");
Run Code Online (Sandbox Code Playgroud)

这样,您在View中所要做的就是说

<a href="@Model.CancelUrl">Text</a>
Run Code Online (Sandbox Code Playgroud)