ASP.NET MVC Generate DropDownList using UIHint Attribute

a 夏天 提交于 2019-12-04 15:12:15

Here's an (untested) general example using generics. There's probably a simpler way of achieving the same thing.

Model:

public class CartProduct
{
    [UIHint("_DropDownList")]
    public DropDownListModel<ItemType> MyItems { get; set; }
}

DropDownListModel class:

public class DropDownListModel<T>
{
    public T SelectedItem { get; set; }

    public IEnumerable<T> Items { get; set; }
}

Controller:

public ActionResult AnAction()
{
    var model = new CartProduct();
    model.MyItems = new DropDownListModel<ItemType>
    {
        Items = _yourListOfItems,
        SelectedItem = _yourSelectedItem
    };

    return View(model);
}

_DropDownList.cshtml editor template:

@model DropDownListModel<object>

@Html.DropDownListFor(m => m.SelectedItem,
    new SelectList(Model.Items, Model.SelectedItem))

And, finally, your view:

@model CartProduct

@Html.EditorFor(m => m.MyItems)

This gives you a generic DropDownListModel that you can use anywhere, with any type. Use EditorFor and UIHint to specify the editor template and reuse the view all over the place.

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