I am just getting started with MVC and I'd like to display two DropDownLists on my index page - index view and populate first dropdown with unique State name from the database and based on the selection from the first dropdown, populate second dropdown with data from Names from the database table where state equals to the state selected in the first dropdownlist.
I already have Model class created and below is my controller:
public ActionResult Index()
{
MyRecordContext rc = new MyRecordContext();
List<MyRecord> rl = rc.MyRecords.ToList();
return View(rl);
}
In my view Index.shtml I have the following to display first dropdownlist:
@if (Model != null)
{
<select id="ddlState">
@foreach (var item in Model)
{
<option>
@item.State
</option>
}
</select>
}
Now how can I ensure that only distinct state is selected from the database and how do I go about creating and populating second dropdown based on selection in the first? Can someone please point me in the right direction? Thank you
Update:
In order to display distinct states in the dropdown, I modified my controller the following way:
public ActionResult Index()
{
MyRecordContext rc = new MyRecordContext();
List<String> sl = rc.MyRecords.Select(s => s.State).Distinct().ToList();
return View(sl);
}