I have two dropdownlistfor
, and the second of them should be filled with an array based on the value of the first dropdownlist
I've tried to follow Darins Answer here but I have problem getting the second dropdownlistfor
to work and filled with my array. My second Dropdownlisfor
is not getting filled, instead, it disappear.
This my script for using JSON
<script type="text/javascript">
$(function () {
$('#teamname').change(function () {
var selectednametext = $(this).find("option:selected").text();
$.getJSON('@Url.Action("TeamName")', { TeamName: selectednametext }, function (persons) {
var selectedpersons = $('#personname');
selectedpersons.empty();
$.each(persons, function (index, person) {
selectedpersons.append(
$('<option/>')
.attr('value', person.name)
.text(person.name)
);
});
});
});
});
</script>
This is my DropdownListfor
in my view:
<p>Team</p>
<div class="editor-field" id="teamname">
@Html.DropDownListFor(model => model.TeamName, Model.Teams, "Select Team", new { @class = "selectstyle" })
@Html.ValidationMessageFor(model => model.TeamName)
</div>
<p>Person</p>
<div class="editor-field" id="personname">
@Html.DropDownListFor(model => model.PersonName, Model.Person, "Select Person", new { @class = "selectstyle", @disabled = "disabled" })
@Html.ValidationMessageFor(model => model.PersonName)
This how my array is getting filled in my controller:
public ActionResult TeamName(string teamname)
{
if (teamname == "Team A")
{
System.Collections.ArrayList teamArray = new System.Collections.ArrayList();
new ConsultantContext(new Uri("http://foo/persons"), ConsultantContext.Format.Json)
.Consultant
.Where(x => x.Team == "Team A")
.OrderBy(x => x.DisplayName)
.ToList()
.ForEach(item =>
{
teamArray.Add(item.DisplayName);
});
return Json(teamArray, JsonRequestBehavior.AllowGet);
}// and same goes with arrays for Team B and Team C
All kind of help is appreciated, thanks in advance!