Reputation: 1014
I have two select lists on a view. I need to populate the second select list's items according to the value of the first select list's selected item without posting the entire page. What is the best way to make this happen?
Here are the select lists in the view:
<tr>
<td>
<div class="editor-label">
@Html.LabelFor(model => model.PersonnelAreaID)
</div>
</td>
<td>
<div class="editor-field">
@Html.DropDownListFor(model => model.PersonnelAreaID, TLMS_DropDownLists.PersonnelAreas)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
@Html.LabelFor(model => model.SupervisorID)
</div>
</td>
<td>
<div class="editor-field">
@Html.DropDownListFor(model => model.PersonnelAreaID, TLMS_DropDownLists.ApprovingAuthorities)
</div>
</td>
</tr>
Here are the methods I am populating them with currently:
public static List<SelectListItem> PersonnelAreas
{
get
{
List<SelectListItem> personnelAreas = new List<SelectListItem>();
personnelAreas.Add(new SelectListItem { Value = "", Text = "" });
foreach (PersonnelArea pa in PersonnelArea.GetAllPersonnelAreas())
{
personnelAreas.Add(new SelectListItem { Value = pa.AreaID.ToString(), Text = pa.AreaTitle });
}
return personnelAreas;
}
private set { }
}
public static List<SelectListItem> ApprovingAuthorities
{
get
{
List<SelectListItem> returned = new List<SelectListItem>();
returned.Add(new SelectListItem { Text = "", Value = "" });
foreach (Employee item in Employee.GetAllEmployees().Where(e => e.UserRoleID == 2 || e.UserRoleID == 5))
{
returned.Add(new SelectListItem { Text = string.Format("{0} {1}", item.FirstName, item.LastName), Value = item.ID.ToString() });
}
return returned;
}
private set { }
}
I need the ApprovingAuthorities select list to show only those applicable to the PersonnelArea.
Upvotes: 1
Views: 5070
Reputation: 7105
You can also use SignalR to populate the second combobox. You can follow a good tutorial here
Upvotes: 0
Reputation: 33139
The "best" way is probably a matter of opinion, but a good way to do it is to use AJAX to populate the 2nd dropdown.
Whereas the first dropdown can be populated with static data, the 2nd can be populated either by generating client-side JavaScript code that fills up the 2nd, or by doing an AJAX call to a Controller method that returns JSON, and then filling up the 2nd dropdown with that data.
Here is a nice article about it: "Cascading Dropdown Lists with MVC 4 and jQuery" at http://www.sidecreative.com/Blog/Entry/Cascading-dropdown-lists-with-MVC4-and-jQuery.
Good luck!
Upvotes: 2