在MVC项目中,首先是EF DB,我使用ViewBag属性在下拉列表中显示值列表。这是我的get方法和post方法.-
[ HttpGet]
public ActionResult Create()
{
using (var context = new AdventureWorksEntities())
{
ViewBag.Colors = new SelectList(context.Products.Select(a =>
a.Color).Distinct().ToList());
}
return View();
[HttpPost]
[ActionName("Create")]
public ActionResult CreatePost()
{
var producttocreate = new Product();
try
{
UpdateModel(producttocreate);
if (ModelState.IsValid)
{
using (var context = new AdventureWorksEntities())
{
context.Products.Add(producttocreate);
context.SaveChanges();
}
return RedirectToAction("Index");
}
return View(producttocreate);
}
catch(Exception e)
{
return View(producttocreate);
}
}
这里的ViewBag.Colors属性是有问题的。当我在Post上获得异常时,我想传递模型并再次返回相同的Create视图。但是,即使每次调用Create Get方法时都有设置ViewBag.Colors的代码,它也没有被设置,并且在创建视图渲染时出现错误 -
具有键“Color”的ViewData项的类型为“System.String”,但必须是“IEnumerable”类型。
我确实在其他帖子中发现这个异常的原因是ViewBag.Colors是null,但我不明白为什么。从Post Action Method调用View时,为什么没有设置?这是什么解决方案?
之前
return View(producttocreate);
这样做
ViewData["Colors"] = new SelectList(_context.Products, "Id", "Color", ColorId);
ViewBag.Colors
为null的原因是因为当POST中出现错误时,您不会重定向到(GET)Create操作。相反,您将模型发送回视图,绕过(GET)Create操作,因此不会填充ViewBag。如果您使用RedirectToAction("Create");
而不是View(producttocreate)
,ViewBag.Colors将再次填充。