I'm working on a project where I need to create a dropdown from a database. The dropdown includes the State where a vendor is located. However, the dropdown is returning duplicate values. The intent is to use the dropdown to filter Vendors by the State they are located in.
Controller:
public ActionResult Index()
{
ViewBag.State = new SelectList
(db.Vendors
.OrderBy(v => v.State)
.Distinct(),
"State", "State");
return View(db.Vendors.ToList());
}
View:
@Html.DropDownList("State", null, "Select State", htmlAttributes: new { @class = "nav-link active", @onchange = "FillByState()" })
I've tried other solutions I found here that seemed to have similar issues.
I attempted this in the Controller:
public ActionResult Index()
{
ViewBag.State = new SelectList
(db.Vendors
.Select(v => v.State)
.Distinct(),
"State", "State");
return View(db.Vendors.ToList());
}
But that kicked back the following Exception:
Exception Details: System.Web.HttpException: DataBinding: 'System.String' does not contain a property with the name 'State'.
At this point, I'm scratching my head as to what I can do.
TLDR:
I'm trying to create a dropdown list of unique values (State). However, what I have tried so far either creates a dropdown of states that appear more than once or throws an exception.
CodePudding user response:
You are on the right track, but once you select the state name (and reduced it using Distinct), you no longer have to specify names for the data value and data text fields in the SelectList constructor. The string itself will serve as both. You probably do still want a sorted list though.
Try
public ActionResult Index()
{
ViewBag.State = new SelectList
(db.Vendors
.Select(v => v.State)
.Distinct()
.OrderBy(s => s));
return View(db.Vendors.ToList());
}