I am using the following code with my MVC Html View
@Html.DropDownListFor(m => m.Company,
new SelectList(ViewBag.Companies, "Key", "Value", Model.Company))
My controller makes the like this:
[HttpGet]
public ActionResult Login()
{
ViewBag.Companies = (from a in _context.Companies
select new {Key = a.Id, Value = a.Name});
return View();
}
But shows the following error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 30: Line 31: Line 32:
@Html.DropDownListFor(m => m.Company, Line 33: new SelectList(ViewBag.Companies, "Key", "Value", Model.Company)) Line 34:
This code is used to so a login screen where its Username, Password and Dropdown for Company.
@modelof your view? In your Controller action you need to pass in an instance to theView()so something like :return View(new YourModel());...Model.Companyin your helper and yourModelis null. Just write@Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Companies, "Key", "Value"))