我有两个dropdownlistfor
,其中第二个应根据第一个dropdownlist
我试图关注Darins Answer here,但我遇到问题,让第二个dropdownlistfor
工作并填充我的数组。我的第二个Dropdownlisfor
没有被填满,而是消失了。
这是我使用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>
在我看来,这是我的DropdownListfor
:
<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)
这是我的数组如何填充我的控制器:
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
所有的帮助都表示赞赏,提前谢谢!
答案 0 :(得分:1)
$('#teamname')
与您的下拉列表的ID不匹配。确保您在标记中分配了相同的ID:
@Html.DropDownListFor(
model => model.TeamName,
Model.Teams,
"Select Team",
new { id = "teamname", @class = "selectstyle" }
)
$('#personname');
选择器也是如此。您应该修复标记,以便这些选择器对应于您的DOM元素。
另外你为什么要使用ArrayList
?这是史前的。使用强类型集合:
public ActionResult TeamName(string teamname)
{
var consultants = new ConsultantContext(
new Uri("http://foo/persons"),
ConsultantContext.Format.Json
)
.Consultant
.Where(x => x.Team == teamname)
.OrderBy(x => x.DisplayName)
.ToList()
.Select(x => new
{
name = x.DisplayName
});
return Json(consultants, JsonRequestBehavior.AllowGet);
}