How do you handle the output of a dynamically generated form in ASP.NET MVC?

后端 未结 4 1777
失恋的感觉
失恋的感觉 2020-12-19 18:00

Say you create a form using ASP.NET MVC that has a dynamic number of form elements.

For instance, you need a checkbox for each product, and the number of products ch

4条回答
  •  不思量自难忘°
    2020-12-19 18:07

    Depending on the binders you are using, this should work:

    <%var i = 0;
      foreach (var product (IList)ViewData["products"]) {%>
          <%=Html.Hidden(string.Format("products[{0}].Id", i), product.Id)%>
          <%=Html.Checkbox(string.Format("products[{0}].Selected", i))%>
          <%=product.Name%>
    <%}%>

    ...which will result in HTML something like this (notice the array notation on the names):

    
    
    Widget
    
    
    Gadget
    

    ...and the controller method that handles the post:

    public ActionResult SelectProducts(IList products)
    {
         ...
    }
    

    Upon binding, products parameter will contain two instances of ProductSelection.

    One caveat is that I have not used the new default binding for complex objects. Rather I am using either the NameValueDeserializer or CastleBind, both from MvcContrib. They both behave this way. I am guessing binding in the Beta will work the same way.

提交回复
热议问题