在ASP.Net MVC中使用DropDownList的最佳编程实践
我正在使用MVC 5几个月阅读了很多文章,论坛和文档,但总是想知道视图中哪个更好;
1)使用这里的模型静态方法绑定数据
2)使用在Controller中设置的ViewData [index]绑定相同的数据,前面的示例将如下所示
@Html.DropDownListFor(n => n.MyColorId, ViewData[index])
您想使用选项1,主要是因为您希望尽可能使用强类型 ,并在编译时修复错误。
相比之下, ViewData和ViewBag是动态的,并且编译在运行时才能捕获错误。
以下是我在许多应用程序中使用的示例代码 –
模型
public class SampleModel { public string SelectedColorId { get; set; } public IList AvailableColors { get; set; } public SampleModel() { AvailableColors = new List (); } }
视图
@model DemoMvc.Models.SampleModel @using (Html.BeginForm("Index", "Home")) { @Html.DropDownListFor(m => m.SelectedColorId, Model.AvailableColors) }
调节器
public class HomeController : Controller { public ActionResult Index() { var model = new SampleModel { AvailableColors = GetColorListItems() }; return View(model); } [HttpPost] public ActionResult Index(SampleModel model) { if (ModelState.IsValid) { var colorId = model.SelectedColorId; return View("Success"); } // If we got this far, something failed, redisplay form // ** IMPORTANT : Fill AvailableColors again; otherwise, DropDownList will be blank. ** model.AvailableColors = GetColorListItems(); return View(model); } private IList GetColorListItems() { // This could be from database. return new List { new SelectListItem {Text = "Orange", Value = "1"}, new SelectListItem {Text = "Red", Value = "2"} }; } }
我会说,从ViewData
完全分离下拉项。 让您的模型包含下拉属性。 在控制器中填充它,然后在视图中绑定它
视图模型
class MyModel { public IEnumerable dropdowndata {get; set;} }
调节器
public Actionresult MyAction(string id) { IEnumerable mydata = callDALmethodtogetit(); Mymodel model = new MyModel { dropdowndata = mydata.Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name }); } }
视图
@Html.DropDownListFor(model => model.dropdowndata, Model.dropdowndata)