soren.enemaerke
soren.enemaerke

Reputation: 4830

ASP.NET MVC form handling unknown number of inputs

I'm building an internal page that allows trusted users to change a parameter setup manually through a form. The inputs to this setup are a list of setupparameters (of unknown size), each with a specific list of values. The user can then select a value for all or a subset of the parameters.

I have attempted to illustrate this with my current model for the view

    public class SetupModel
    {
        public List<SetupParameter> Parameters { get; set; }
    }

    public class SetupParameter
    {
        public string ParameterName { get; set; }

        // list with text=paramvalue, value=paramvalueid 
        public SelectList ParameterValueList { get; set; } 
        // id of the selected parametervalue if any
        public int? SelectedParameterValueID { get; set; }
    }

My current attempt at rendering a view for this:

<% using (Html.BeginForm("Update", "Parameters") {%>
...
<% foreach( var parameter in Model.Parameters ) { %>
            <div><%: parameter.ParameterName %></div>
            <div><%: Html.DropDownListFor(x => parameter.SelectedParameterValueID, parameter.ParameterValueList, "Please select") %></div>

<% } %>
...

My question is how can I render a view that allows me to submit the form and get a reasonably understandable model back to my form action that will allow me to obtain the list of selected parameter values. I'm not aware of the best practices or tricks here, so I will appreciate any feedback I get :)

Upvotes: 4

Views: 1693

Answers (2)

Rob
Rob

Reputation: 10248

You could try using a FormCollection:

public ActionResult Submit(FormCollection formCollection)
{
     //Iterate form collection to get fields

     return View();
}

Upvotes: 4

CGK
CGK

Reputation: 2662

You might find this post by Phil Haack useful: Model Binding To A List.

Also note that you'll need to post back an identifier (ParameterName, for example) for each parameter too, so you can indentify which value corresponds to a parameter back in the controller.

Upvotes: 0

Related Questions