在 ASP.Net MVC 中使用 DropDownList 的最佳编程实践 [英] Best programming practice of using DropDownList in ASP.Net MVC
问题描述
我用 MVC 5 工作了几个月,阅读了很多文章、论坛和文档,但总是想知道在视图中什么更好;
I'm working with MVC 5 for a few months read a lot of articles, forums and documentation but always wondering what is better in the view;
1) 使用模型的静态方法绑定数据,例如 here
1) binding data using static method of model like here
2) 使用在控制器中设置的 ViewData[index] 绑定相同的数据,与前面的例子一样
2) binding the same data using ViewData[index] which is set in Controller that with previous example will look like this
@Html.DropDownListFor(n => n.MyColorId, ViewData[index])
推荐答案
你想使用选项1,主要是你想尽可能使用Strongly Type,并在编译时修复错误时间.
You want to use option 1, mainly because you want to use Strongly Type as much as possible, and fix the error at compile time.
相比之下,ViewData 和 ViewBag 是动态的,编译直到运行时才能捕获错误.
In contrast, ViewData and ViewBag are dynamic, and compile could not catch error until run-time.
这是我在许多应用程序中使用的示例代码 -
Here is the sample code I used in many applications -
public class SampleModel
{
public string SelectedColorId { get; set; }
public IList<SelectListItem> AvailableColors { get; set; }
public SampleModel()
{
AvailableColors = new List<SelectListItem>();
}
}
查看
@model DemoMvc.Models.SampleModel
@using (Html.BeginForm("Index", "Home"))
{
@Html.DropDownListFor(m => m.SelectedColorId, Model.AvailableColors)
<input type="submit" value="Submit"/>
}
控制器
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<SelectListItem> GetColorListItems()
{
// This could be from database.
return new List<SelectListItem>
{
new SelectListItem {Text = "Orange", Value = "1"},
new SelectListItem {Text = "Red", Value = "2"}
};
}
}
这篇关于在 ASP.Net MVC 中使用 DropDownList 的最佳编程实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!