Converting HTML.EditorFor into a drop down (html.dropdownfor?)

时间秒杀一切 提交于 2019-11-27 13:16:51

In order to generate a dropdownlist you need 2 properties on your view model: a scalar property to bind the selected value to and a collection property which will contain the items to show in the dropdown.

So you could define a view model:

public class DropDownListViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then on your main view model have a property of this type:

public DropDownListViewModel Foo { get; set; }

Now you could have a custom editor template for this type (~/Views/Shared/EditorTemplates/DropDownListViewModel.ascx):

<%@ Control 
    Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DropDownListViewModel>" 
%>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>

and then in your main view:

<%= Html.EditorFor(x => x.Foo) %> 

Now all that's left is to have your controller action rendering the main view to fill the Foo property with the corresponding values. The could be hardcoded, come from a repository or whatever. It doesn't really matter.

On the other hand if you knew the values in advance you could hardcode them in the editor template (~/Views/Shared/EditorTemplates/YesNoDropDown.ascx):

<%= Html.DropDownList(
    "", 
    new SelectList(
        new[] 
        { 
            new { Value = "true", Text = "Yes" },
            new { Value = "false", Text = "No" },
        }, 
        "Value", 
        "Text",
        Model
    )
) %>

and then:

<%= Html.EditorFor(x => x.IsActive, "YesNoDropDown") %> 

or by decorating the IsActive property on your view model:

[UIHint("YesNoDropDown")]
public bool IsActive { get; set; }

and then:

<%= Html.EditorFor(x => x.IsActive) %> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!