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; }
}
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.