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
Ah misunderstood this.
If you know what Dropdowns can potentially be added, I would always just have a value on your model. MVC will set them as a default value if nothing is received.
EDIT: You can still access the forms collection in a more raw way from withing controllers using
Of course these will be all values posted by your form so you will need a way to recognise one of your dropdowns like a prefix or something. For example
I still don’t really understand how you intend to process the dynamic dropdowns if you don’t know what they will be and this can cause some issues and will make validation entirely dynamic and client side (not 100% safe). That could present some security issues as well, but there are some sceanarios where you might use this and I’ll assume you have one of them.
If that’s not the case, don’t forget that just because a Model has a property, it doesn’t have to be posted back at all.
You could do:
The controller will do it’s best to populate the model, but if you don’t pass some fields back from the form, they will just be null and the action will still work.
I have also implemented much more complex scenarios like this using objects that are children of the parent model and all nullable. That requires a bit of fancy work around ajax calls to EditorTemplates in mock Views to ensure the prefixing is right for MVC to parse, but I won’t go into that here.