ASP.NET MVC - 表单的动态操作和参数

时间:2009-11-25 14:40:07

标签: asp.net-mvc

我正在研究一些MVC,我需要动态地将表单路由到某个动作和参数组合。到目前为止,我有这个:

PageViewModel
{
  public string Action {get;set;}
  public string Parameter {get;set;}
  /*... other properties for the form */
}

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"));
  }
  /* ... and about 15 more of these */
}

CommonView.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" />
<%}%>

或者,是否有办法获取用于生成此视图的操作和参数,可能来自路径数据?

或者是否应该有自动处理所有这些的自定义路由方案?

所以,我真正想要的是实现这一目标的最优雅和类型安全的方法。谢谢!

修改

正如Josh所指出的那样,表格将提交回行动。这有点修改了代码:

PageViewModel
{
  public string ParameterName {get;set;}
  /*... other properties for the form */
}

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"));
  }
  /* ... and about 15 more of these */
}

CommonView.aspx:

<%-- ... --%>
<% using (Html.BeginForm(FormMethod.Get)) {%>
    <%=Html.TextBox(Model.ParameterName)%>
    <input id="submit" type="submit" value="Submit" />
<%}%>
<%-- ... --%>

目前还不清楚如何让文本框按名称将参数绑定回创建视图的操作,而不是明确指定它。

1 个答案:

答案 0 :(得分:0)

  

或者,是否有办法获取用于生成此视图的操作和参数

如果将BeginForm参数的动作和控制器部分留空,它将回发到它来自的位置。你可以有两个同名的动作,一个装饰为HttpGet,另一个装饰为HttpPost,只要它们有不同的参数。通常get有一个或没有,post有几个或模型绑定。