1

I have made a View named ManageSalesman, it has two sub Views named AddOrEdit and it contains a form. Here I want to populate the Vendor companies list in the drop down from the Vendor table in the database, for that I get them in view bag in the following code.

ViewBag.Vendor = new SelectList(db.Vendors, "Id", "name");

and make drop down list in AddOrEdit by the following line of code.

 @Html.DropDownListFor(model => model.CompanyId, new SelectList(ViewBag.Vendor, "Id", "name"), "Select Vendor Company", new { @class = "form-control" })

but when I run it, it will show me: Argument null exception "Additional information: Value cannot be null." Kindly tell me what I am doing wrong.

Guilherme Holtz
  • 474
  • 6
  • 19
Hacan Champ
  • 53
  • 11

2 Answers2

1

Use the below code for creating the dropdown control.

@Html.DropDownListFor(model => model.CompanyId, (SelectList)ViewBag.Vendor, "Select Vendor Company", new { @class = "form-control" })

Please refer this question has more details.

SMR
  • 136
  • 5
  • now i am getting {"The ViewData item that has the key 'CompanyId' is of type 'System.Int32' but must be of type 'IEnumerable'."} while i think it is in IEnumerable. – Hacan Champ Feb 12 '18 at 18:28
  • @HacanChamp, for that error, refer [The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) –  Feb 12 '18 at 23:10
  • I have added " ViewBag.Vendor = new SelectList(db.Vendors, "Id", "name"); " in POST Action result but still getting same error. – Hacan Champ Feb 13 '18 at 06:08
0

I have not make a list of selected vendor in a controller.The correct way is as follow.

List<Vendor> VendorList = db.Vendors.ToList();
ViewBag.Vendor = new SelectList(VendorList, "Id", "name");
Hacan Champ
  • 53
  • 11