Search code examples
c#asp.net-mvcviewbagselectlistitem

ViewBag property not getting set when get action is called


In MVC project,EF DB first, I am using a ViewBag property to show a list of values in a dropdown. Here is my get method and post method for the same.-

[ 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);
            }

    }

Here the property ViewBag.Colors is the proprty in question. When I am getting an exception on Post I want to pass the model and return the same Create view again. However , even though I have code to set ViewBag.Colors everytime the Create Get method is called , it is not being set and I am getting an error when Create View is rendering -

The ViewData item that has the key 'Color' is of type 'System.String' but must be of type 'IEnumerable'.

I did find out in some other post that the reason for this exception is that ViewBag.Colors is null , but I do not understand why. Why is it not getting set when View is called from Post Action Method? And what is the solution to this?


Solution

  • Before

    return View(producttocreate);
    

    do like this

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