我使用 MVC 5 几个月了,阅读了大量文章、论坛和文档,但总是想知道视图中什么更好;
1)使用模型的静态方法绑定数据,例如here
2)使用在控制器中设置的 ViewData[index] 绑定相同的数据,前面的示例将如下所示
@Html.DropDownListFor(n => n.MyColorId, ViewData[index])
你想使用选项1,主要是因为你想使用强型尽可能地,并在编译时修复错误。
相比之下,ViewData and ViewBag是动态的,编译直到运行时才能捕获错误。
这是我在许多应用程序中使用的示例代码 -
Model
public class SampleModel
{
public string SelectedColorId { get; set; }
public IList<SelectListItem> AvailableColors { get; set; }
public SampleModel()
{
AvailableColors = new List<SelectListItem>();
}
}
View
@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"}
};
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)