Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 changes day by day.

How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.

like image 897
James Avatar asked Jan 25 '23 01:01

James


1 Answers

Just give each checkbox a unique name value:

<input class="approveCheck" id="<%= "approveCheck" + recordId %>" 
 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.

like image 183
Craig Stuntz Avatar answered Jan 29 '23 23:01

Craig Stuntz