Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting Dynamic Forms in ASP.NET MVC 3

On one of the forms I am working on, if the user selects DropDownList "Type", based on the value selected, I would show Dynamically a set of other DropDownLists.

For instance, Types: Car, Apartment Selecting "Car", would dynamically add two new DropDownLists "Price" & "Model". Selecting "Building", would dynamically add two new DropDownLists "Area" & "Floor"

My question is how to handle the posted data to server? I would typically receive the form's fields and they get "model bound" automatically. But what about those dynamic fields that were added on the page based on user's selection? How will I retrieve them inside the Action?

Thanks

like image 980
Bill Avatar asked Mar 09 '12 00:03

Bill


1 Answers

You can use the FormCollection to access all the fields on the page. However you'll lose the automatic model binding and will have to iterate through the form collection to find your values as follows:

public ActionResult ActionMethod(FormCollection formCollection)
{
    foreach (var key in formCollection.AllKeys)
    {
        var value = formCollection[key];
    }
}

Of course you could also just include the dynamic dropdowns in your model.

like image 142
Mark Avatar answered Sep 30 '22 19:09

Mark