Search code examples
asp.net-mvcmodel-view-controllerdropdownviewbag

Access data from Viewbag Dropdown


I am getting the value from dropdown to controller but when it goes back to View it returns Null SCREENSHOT OF VIEW:- enter image description here

SCREENSHOT OF CONTROLLER:-

public ActionResult Index(int departmentID)
{
     ViewBag.dropdowndetail = null;
 
    var strDDLValue = departmentID;
    if (strDDLValue == null)
    {
        return HttpNotFound();
    }
    else
    {
        var emp = db.employees.ToList().FirstOrDefault(x=>x.depId==departmentID);
        return View(emp);
    }
}

ERROR: enter image description here


Solution

  • I get it right My viewbag was not getting any value in Post method so that why in View it was getting null Exception I call my viewbag in Post method and give it the value. change the following code with this.

     public ActionResult Index(int departmentID)
        {         
            var strDDLValue = departmentID;
            if (strDDLValue == null)
            {
                return HttpNotFound();
            }
            else
            {
                var emp = db.employees.Where(x=>x.depId==departmentID).ToList();
                ViewBag.dropdowndetail = db.departments.Distinct().ToList();
                return View(emp);
            }
    
        }