0

我有两个dropdownlistfor,第二个应该根据第一个的值填充一个数组dropdownlist

我试图在这里遵循 Darins Answer,但我无法让第二个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

感谢您提供各种帮助,在此先感谢!

4

1 回答 1

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);   
}
于 2012-05-15T14:03:21.933 回答