ASP.NET MVC Generate DropDownList using UIHint Att

2020-07-25 10:33发布

I would like to know how can I generate a DropDownList using an UIHint attribute. I already customized some of the predefined attributes but I don't know how to proceed for generating DropDownLists.

Here is how I did with my last one and I want to use it in a similar way:

public class CartProduct
{

    [Required]
    [UIHint("Spinner")]
    public int? Quantity { get; set; }

    [Required]
    [UIHint("MultilineText")]
    public string Description { get; set; }

}

1条回答
我命由我不由天
2楼-- · 2020-07-25 10:42

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.

查看更多
登录 后发表回答