Khizar Nayyar
Khizar Nayyar

Reputation: 388

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

Upvotes: 1

Views: 524

Answers (2)

Farruk
Farruk

Reputation: 31

You can use keyvalue approach in controller

ViewBag.dropdowndetail = db.departments.Distinct().Select(x => new KeyValuePair<int, string>(x.depid, x.DepartmentName));

and in View use ViewBag like this

 @Html.DropDownListFor(model => model.depid, new SelectList((IEnumerable<KeyValuePair<int, string>>)ViewBag.dropdowndetail , "key", "value"), "--Select Departments--")

Upvotes: 1

Khizar Nayyar
Khizar Nayyar

Reputation: 388

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

    }

Upvotes: 3

Related Questions