我正在处理一些MVC,在这里我需要动态地将表单路由到某个动作和参数组合。到目前为止,我得到了:
PageViewModel
{
public string Action {get;set;}
public string Parameter {get;set;}
}
PageController
{
public ViewResult MyAction(string myParamterName) {
return View("CommonView",
new PageViewModel{Action="MyAction", Parameter="myParameterName"));
}
public ViewResult YourAction(string yourParamterName) {
return View("CommonView",
new PageViewModel{Action="YourAction", Parameter="yourParameterName"));
}
}
通用视图.aspx:
<%-- ... --%>
<% using (Html.BeginForm(Model.Action,"PageController",FormMethod.Get)) {%>
<%=Html.TextBox(Model.Parameter)%>
<input id="submit" type="submit" value="Submit" />
<%}%>
<%-- ... --%>
这是可行的,但它有很多字符串在周围浮动,告诉它去哪里。
我想要的是一种类型安全的方式来定义视图中的表单参数,但是我对如何实现这一点有点迷茫。可能是像这样的东西-
<% using (Html.BeginForm<PageController>(Model.??ExpressionToGetAction??)) {%>
<%=Html.TextBox(Model.??ExpressionToGetParameter??)%>
<input id="submit" type="submit" value="Submit" />
<%}%>
或者,是否有一种方法可以从路由数据中获取用于生成此视图的操作和参数?
或者应该有一个可以自动处理所有这些问题的自定义路由方案?
所以,我真正想要的是实现这一点的最优雅和类型安全的方法。谢谢!
编辑
正如乔希指出的,表格将提交回行动。这会稍微简化代码:
PageViewModel
{
public string ParameterName {get;set;}
}
PageController
{
public ViewResult MyAction(string myParamterName) {
return View("CommonView",
new PageViewModel{ParameterName ="myParameterName"));
}
public ViewResult YourAction(string yourParamterName) {
return View("CommonView",
new PageViewModel{ParameterName ="yourParameterName"));
}
}
通用视图.aspx:
<%-- ... --%>
<% using (Html.BeginForm(FormMethod.Get)) {%>
<%=Html.TextBox(Model.ParameterName)%>
<input id="submit" type="submit" value="Submit" />
<%}%>
<%-- ... --%>
不清楚如何让文本框按名称将参数绑定回创建视图的操作,而不显式指定该操作。