简体   繁体   中英

Asp.Net MVC Handle Drop Down Boxes that are not part of the Model

I have a small form which the user must fill in and consists of the following fields.

Name (Text) Value (Text) Group (Group - Is a list of option pulled from a database table)

Now the Model for this View looks like so,

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

Now the view is Strongly Typed to the above model.

What method would one use to populate the drop down list? Since the data is not contained within the Model (It could be contained in the Model) should we be using Temp/View data? A HTML Helper? What would be the ideal way to achieve this.

I use a viewmodel for this with a dictionary (I like mvc contrib's select box) containing all the properties something 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'll only need to do

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

Hope it helps.

NOTE: this assumes you are using MVC2.

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

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

I do a pre-conversion of my list to an IEnumerable<SelectListItem> in my action using code similar to this. (This assumes a country class with a name and unique ID).

        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 post back to a strongly typed action (receiving the same viewmodel back), the CountryID will be the ID of the selected country.

The other benefit, if they have an issue with the validation. All you need to do is repopulate the .Countries list, pass the viewmodel back into the view and it will automatically select the the correct value.

I like the following approach: Have a helper class that does this things 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 */
       // f.e. set the item that matches model.GroupId already as selected
    }
 }

Add in your model:

 public DropdownLogic Groups { get; set; }

And in your view:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM