首页 > 解决方案 > 调用 get 操作时未设置 ViewBag 属性

问题描述

在 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 呈现时出现错误 -

具有键 'Color' 的 ViewData 项属于 'System.String' 类型,但必须属于 'IEnumerable' 类型

我确实在其他一些帖子中发现此异常的原因是 ViewBag.Colors 为 null ,但我不明白为什么。为什么从 Post Action 方法调用 View 时没有设置它?解决方案是什么?

标签: c#asp.net-mvcviewbagselectlistitem

解决方案


return View(producttocreate);

这样做

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

推荐阅读