代码之家  ›  专栏  ›  技术社区  ›  James Kolpack

ASP.NET MVC-窗体的动态操作和参数

  •  1
  • James Kolpack  · 技术社区  · 15 年前

    我正在处理一些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 */
    }
    

    通用视图.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;}
      /*... 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 */
    }
    

    通用视图.aspx:

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

    不清楚如何让文本框按名称将参数绑定回创建视图的操作,而不显式指定该操作。

    1 回复  |  直到 15 年前
        1
  •  0
  •   Josh Pearce    15 年前

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

    如果您将begininform参数的action和controller部分留空,它将返回到它来自的位置。您可以有两个同名的操作,一个修饰为httpget,另一个修饰为httppost,只要它们有不同的参数。通常get有一个或没有,post有多个或一个模型绑定。