0

私は 2 つ持っておりdropdownlistfor、そのうちの 2 つ目は、最初の値に基づいた配列で満たす必要があります。dropdownlist

ここでDarins Answerに従おうとしましたが、2 番目の配列を機能させるのに問題がありdropdownlistfor、配列がいっぱいになりました。私の 2 番目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 に答える