ASP.NET MVC form handling unknown number of inputs

廉价感情. 提交于 2019-12-06 05:35:27

问题


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 :)


回答1:


You could try using a FormCollection:

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

     return View();
}



回答2:


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.



来源:https://stackoverflow.com/questions/4389214/asp-net-mvc-form-handling-unknown-number-of-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!