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

后端 未结 4 1788
失恋的感觉
失恋的感觉 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:25

    Just give each checkbox a unique name value:

    " 
     name="<%= "approveCheck" + recordId %>" type="checkbox" />
    

    Then parse the list of form values in the Action, after submit:

    foreach (var key in Request.Form.Keys)
        {
            string keyString = key.ToString();
            if (keyString.StartsWith("approveCheck", StringComparison.OrdinalIgnoreCase))
            {
                string recNum = keyString.Substring(12, keyString.Length - 12);
    
                string approvedKey = Request.Form["approveCheck" + recNum];
                bool approved = !String.IsNullOrEmpty(approvedKey);
                // ...
    

    You don't need to pass form values as arguments; you can just get them from Request.Form.

    One other option: write a model binder to change the list into a custom type for form submission.

提交回复
热议问题