Using a dynamic list of checkboxes in a view, how to create a model

I have an asp mvc 2 app lication where I want to display a list of checkboxes that the user can select based on the list of records in the database. To display a list, my model contains a List object, and the view has a foreach and outputs an Html.CheckBox for each item in the list.

Is there a way to get a model filled with selected checkboxes, given that the model cannot have specific properties for each checkbox because the list is dynamic? Or do I need to manually manually iterate over form variables?

Edit: additional data according to sabanito comment Therefore, in a simple view / simulation, if my model had Property1, then my view returned a text box for Property1, when the form is submitted via the submit button, the mvc structure will automatically populate Property1 containing The text that was entered into the text box and passed this model to the action of the controllers.

Since I am dealing with a dynamic list of parameters that the user could check, I cannot write explicit logical properties in my model and explicitly create check boxes in my view. Given that my list is dynamic, I wonder if there are ways to create my model and see if the mvc structure can correctly fill in the model when submitting the form.

+3
source share
2 answers

Here is what I will do:

Do you have any problems generating checkbox dynamically?

If not, create a property in your ViewModel that:

public List<string> CheckboxResults { get; set; }

When you create your checkbox in the view, make sure they all share the name = "CheckboxResults". When MVC sees your ViewModel as a parameter in the action method, it automatically binds and returns all the "CheckboxResults" results in the List (as well as your other ViewModel properties). Now you have a dynamic list, based on which the checkbox that your user checked is checked, you can send it to DomainModel or anywhere.

. , , , .

+3

ViewModel, , .

, , . , , TON . , ViewModel, 1:1 .

+1

Source: https://habr.com/ru/post/1727657/


All Articles