rk1*_*962 0 asp.net-mvc asp.net-mvc-3
我在MVC3应用程序中有两个按钮.
<input type="submit" name="command" value="Transactions" />
<input type="submit" name="command" value="All Transactions" />
Run Code Online (Sandbox Code Playgroud)
当我单击一个按钮时,它会正确回发,但FormCollection没有"命令"键.我还在模型中添加了一个属性"command",并且在发布表单时它的值为null.
public ActionResult Index(FormCollection formCollection, SearchReportsModel searchReportsModel). {
if (searchReportsModel.command == "All Transactions")
...
else
....
}
Run Code Online (Sandbox Code Playgroud)
我正在使用IE8.如何在MVC3中使用多个按钮?这个问题有解决方法吗?我做了很多研究,找不到解决方案.
更新:
戴夫:我尝试了你的解决方案,它正在抛出Http 404错误"无法找到资源".
这是我的代码:
[HttpPost]
[AcceptSubmitType(Name = "Command", Type = "Transactions")]
public ActionResult Index(SearchReportsModel searchReportsModel)
{
return RedirectToAction("Transactions", "Reports", new { ...});
}
[HttpPost]
[ActionName("Index")]
[AcceptSubmitType(Name = "Command", Type = "All Transactions")]
public ActionResult Index_All(SearchReportsModel searchReportsModel)
{
return RedirectToAction("AllTransactions", "Reports", new { ... });
}
public class AcceptSubmitTypeAttribute : ActionMethodSelectorAttribute
{
public string Name { get; set; }
public string Type { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
return controllerContext.RequestContext.HttpContext
.Request.Form[this.Name] == this.Type;
}
}
Run Code Online (Sandbox Code Playgroud)
在ViewModel(SearchReportsModel)中注释以下远程验证属性后,问题得以解决.看起来它是MVC3中的一个错误:
//[Remote("CheckStudentNumber", "SearchReports", ErrorMessage = "No records exist for this Student Number")]
public int? StudentNumber { get; set; }
Run Code Online (Sandbox Code Playgroud)
您可能能够使用ActionMethodSelectorAttribute 属性并覆盖IsValidForRequest方法.您可以在下面看到此方法只是确定特定参数(Name)是否与其中一个属性(Type)匹配.它应该与看起来像这样的视图模型绑定:
public class TestViewModel
{
public string command { get; set; }
public string moreProperties { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该属性可能如下所示:
public class AcceptSubmitTypeAttribute : ActionMethodSelectorAttribute
{
public string Name { get; set; }
public string Type { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
return controllerContext.RequestContext.HttpContext
.Request.Form[this.Name] == this.Type;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下AcceptSubmitType属性标记您的操作:
[AcceptSubmitType(Name="command", Type="Transactions")]
public ActionResult Index(TestViewModel vm)
{
// use view model to do whatever
}
// to pseudo-override the "Index" action
[ActionName("Index")]
[AcceptSubmitType(Name="command", Type="All Transactions")]
public ActionResult Index_All(TestViewModel vm)
{
// use view model to do whatever
}
Run Code Online (Sandbox Code Playgroud)
这也消除了单个控制器操作中逻辑的需要,因为它似乎真的需要两个单独的操作过程.
| 归档时间: |
|
| 查看次数: |
7312 次 |
| 最近记录: |