Hacan Champ
Hacan Champ

Reputation: 53

Populating Drop down list with ViewBag in Asp.net

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.

Upvotes: 1

Views: 1777

Answers (2)

Hacan Champ
Hacan Champ

Reputation: 53

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

Upvotes: 0

SMR
SMR

Reputation: 136

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.

Upvotes: 1

Related Questions