Asp.Net MVC Handle Drop Down Boxes That Are Not Part Of The Model

I have a small form that the user must fill out and consists of the following fields.

Name (text) Value (text) Group (group is a list of parameters derived from the database table)

Now the model for this view looks like this

public string Name { get; set; } public string Value { get; set; } public int GroupID { get; set; } 

Now the view is heavily superimposed on the above model.

What method can be used to populate the drop-down list? Since the data is not contained in the model (it may be contained in the model), should Temp / View data be used? HTML helper? What would be the perfect way to achieve this.

+4
source share
3 answers

NOTE: it is assumed that you are using MVC2.

If I ever need a strongly typed drop-down menu (list of countries in this case), I use 2 properties in my ViewModel.

  public IEnumerable<SelectListItem> Countries { get; set; } public int CountryID { get; set; } 

I am doing a preliminary conversion of my list to IEnumerable<SelectListItem> in my action using code like this. (This assumes a country class with a name and a unique identifier).

  viewModel.Countries = Repository.ListAll().Select(c => new SelectListItem { Text = c.Name, Value = c.ID }); 

Then in my strongly typed view, I use:

  <%= Html.DropDownListFor(model => model.CountryID, Model.Countries) %> 

This is great because when you send back to a strongly typed action (getting the same CountryID mode), CountryID will be the identifier of the selected country.

Another advantage is if they have a verification problem. All you have to do is populate the .Countries list, pass the view model back to the view and automatically select the correct value.

+2
source

I use viewmodel for this with a dictionary (I like the mvc contrib selection box) containing all the properties, like:

 class LeViewModel { public string Name { get; set; } public string Value { get; set; } public int GroupID { get; set; } public Dictionary<string, string> Groups {get; set;} } 

Then in your view you will only need

 <%: Html.Select(m => m.GroupId).Options(Model.Groups) %> 

Hope this helps.

+3
source

I like the following approach: have a helper class that does this for you, something like (pseudo):

 class DropdownLogic { public DropdownLogic(MyModel model) { /* blah */ } public ListOfDropdownItems ToDropdown() { /* do something with model and transform the items into items for the dropdownlist */ // fe set the item that matches model.GroupId already as selected } } 

Add to your model:

  public DropdownLogic Groups { get; set; } 

And in your opinion:

 <%=Html.Dropdown(Model.Groups.ToDropdown())%> 
+1
source

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


All Articles