调用get操作时未设置ViewBag属性

时间:2019-04-11 18:47:41

标签: c# asp.net-mvc viewbag selectlistitem

在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的代码,也没有设置它,并且在渲染Create View时出现错误-

键为“颜色”的ViewData项的类型为“ System.String”,但必须类型为“ IEnumerable”

我确实在其他文章中发现发生此异常的原因是ViewBag.Colors为null,但我不明白为什么。从后期动作方法调用View时为什么没有设置?对此有什么解决方案?

2 个答案:

答案 0 :(得分:0)

之前

return View(producttocreate);

这样做

ViewData["Colors"] = new SelectList(_context.Products, "Id", "Color", ColorId);

答案 1 :(得分:0)

ViewBag.Colors为null的原因是因为POST中发生错误时,您没有重定向到(GET)Create操作。而是将模型发送回视图,绕过(GET)Create操作,从而不会填充ViewBag。如果您使用RedirectToAction("Create");而不是View(producttocreate),则会再次填充ViewBag.Colors。

相关问题