Thursday, 5 September 2013

How can one populate an MVC select list according to selected item from another select list on the same view?

How can one populate an MVC select list according to selected item from
another select list on the same view?

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.

No comments:

Post a Comment