@Html.EditorForModel() Dropdown

前端 未结 2 897
傲寒
傲寒 2020-12-20 06:06

I am working on MVC4 , using @Html.EditorForModel() , it is showing dropdownlist as a text box, I want to show Dropdown

相关标签:
2条回答
  • 2020-12-20 06:08

    You could define a view model that will represent a dropdown:

    public class ItemsViewModel
    {
        public string SelectedValue { get; set; }
    
        public IEnumerable<SelectListItem> Values { get; set; }
    }
    

    which will be used in your main view model:

    public class MyViewModel
    {
        public ItemsViewModel DropDown1 { get; set; }
        public ItemsViewModel DropDown2 { get; set; }
        ...
    }
    

    Now all that's left is write a custom editor template for the ItemsViewModel which should be placed in ~/Views/Shared/EditorTemplates/ItemsViewModel.cshtml. Notice that the name and location of the template is important:

    @model ItemViewModel
    @Html.DropDownListFor(x => x.SelectedValue, Model.Values)
    

    and that's pretty much all it takes.

    0 讨论(0)
  • 2020-12-20 06:33

    It's the overriding template a requisite? You could use the @Html.DropDownList() helper.

    There is a full example about how to use in the asp.net website and you can download the project: Here

    0 讨论(0)
提交回复
热议问题