ASP.NET MVC使用UIHint属性生成DropDownList

我想知道如何使用UIHint属性生成DropDownList。 我已经定制了一些预定义的属性,但我不知道如何继续生成DropDownLists。

以下是我对最后一个的处理方式,我希望以类似的方式使用它:

public class CartProduct { [Required] [UIHint("Spinner")] public int? Quantity { get; set; } [Required] [UIHint("MultilineText")] public string Description { get; set; } } 

这是一个使用generics的(未经测试的)一般示例。 实现同样的事情可能有一种更简单的方法。

模型:

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

DropDownListModel类:

 public class DropDownListModel { public T SelectedItem { get; set; } public IEnumerable Items { get; set; } } 

控制器:

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

_DropDownList.cshtml编辑器模板:

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

最后,您的观点:

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

这为您提供了一个通用的DropDownListModel ,您可以在任何地方使用任何类型。 使用EditorForUIHint指定编辑器模板并在整个地方重用视图。