1
votes

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

2
Be more descriptiveCybercop
From dropdownlist i want show the data of only those employee whose ID I am selecting through Dropdownlist Inshort I want to search through dropdownKhizar Nayyar
@KhizarNayyar do you mean when you POST the form data and then return to the View, the dropdown data is null? If so, this is because you ALSO need to populate ViewBag.dropdowndetail on the POST action before you return the View. ViewBag only lasts for the current request.scgough
You mean In the Post Index method I should use ViewBag.dropdowndetail as well?Khizar Nayyar
@KhizarNayyar yes, you need to populate it in there as well if you intend to use it again in the View of that Controller method. ViewBag will be empty when you POST the formscgough

2 Answers

3
votes

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

    }
1
votes

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--")