Creating a dropdownlist from your controller or view model

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 16:08:04

In your model, change the IList<Category> to SelectList and then instantiate it like this...

List<ParentCategory> parentCategories = categoryService.GetParentCategories();

parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"});

ParentCategories = new SelectList(parentCategories, "Id", "Name");

Then in your view you can simply call

@Html.DropDownListFor(m => m.ParentCategoryId, Model.ParentCategories);

One way I've seen it done is to create an object to wrap the id and value of the drop down item, like a List<SelectValue>, and pass it in your ViewModel to the view and then use an HTML helper to construct the dropdown.

public class SelectValue
{
    /// <summary>
    /// Id of the dropdown value
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Display string for the Dropdown
    /// </summary>
    public string DropdownValue { get; set; }
}

Here is the view model:

public class TestViewModel
{
    public List<SelectValue> DropDownValues {get; set;}
}

Here is the HTML Helper:

public static SelectList CreateSelectListWithSelectOption(this HtmlHelper helper, List<SelectValue> options, string selectedValue)
{
    var values = (from option in options
                  select new { Id = option.Id.ToString(), Value = option.DropdownValue }).ToList();

    values.Insert(0, new { Id = 0, Value = "--Select--" });

    return new SelectList(values, "Id", "Value", selectedValue);
}

Then in your view you call the helper:

@Html.DropDownList("DropDownListName", Html.CreateSelectListWithSelect(Model.DropDownValues, "--Select--"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!