0

行を動的に追加するボタンと、行を削除する方法を備えたテーブルのあるページがあります。各行には、カスケードする 2 つのドロップダウン リストがあります。行が作成されたら、AJAX 呼び出しを使用して最初のドロップダウンに値を入力します。このドロップダウンの変更イベントで、別の AJAX 呼び出しを実行して、2 番目のドロップダウンを設定します。これはすべて正常に機能しますが、私の問題は、最初に表示されるはずのデータを画面にロードすると、ドロップダウンに AJAX 呼び出しを入力できますが、値が選択されていないことです。モデル。この状況を通常処理する方法はありますか? 以下は、私のドキュメント準備完了関数のコードです

$(document).ready(function () {
    $.getJSON('@Url.Action("GetAll", "Customers")', function (customers) {
        var customerSelect = $('.Customers');
        customerSelect.empty();
        customerSelect.append('<option value="0">Choose Customer...</option>');
        $.each(customers, function (index, customer) {
            customerSelect.append($('<option/>', {
                value: customer.ID,
                text: customer.CustomerName
            }));
        });
    });
});

この情報が役立つ場合は、テーブルをロードする HTML コードを次に示します。

<table id="Attendees" class="table-gridview">
        <thead>
            <tr>
                <th style="width:320px">
                    Customer
                </th>
                <th style="width:250px">
                    Attendee
                </th>
                <th>
                    Attended
                </th>
                <th>
                    Paid
                </th>
                <th style="width:120px">
                    Check Number
                </th>
                <th>

                </th>
            </tr>
        </thead>
        <tbody>
            @Html.EditorFor(x => x.Attendees)
        </tbody>
    </table>

次のコードは、出席者用のエディター テンプレートにあるものです。

<tr class="ClassAttendee">

    <td>
        @Html.HiddenFor(model => model.ID)
        @Html.HiddenFor(model => model.ClassID)

        @Html.DropDownList("Customers", Enumerable.Empty<SelectListItem>(), new { @Class = "Customers", style="width:300px" })
    </td>
    <td>    
        @Html.DropDownListFor(
            x => x.CustomerEmailID,
            Enumerable.Empty<SelectListItem>(),
            "Choose Attendee...",
                              new { @Class = "Contact", style = "width:220px" }
        )
        @Html.ValidationMessageFor(model => model.CustomerEmailID)
    </td>
    <td>    
        @Html.CheckBoxFor(model => model.Attended)
        @Html.ValidationMessageFor(model => model.Attended)
    </td>
    <td>    
        @Html.CheckBoxFor(model => model.FeePaid, new { @Class = "FeePaid"})
        @Html.ValidationMessageFor(model => model.FeePaid)
    </td>
    <td>    
        @if (Model.FeePaid != true)
        {
            @Html.TextBoxFor(model => model.CheckNumber, new { @Class = "CheckNumber", disabled ="true", style = "width:100px" })
        }
        else
        {
            @Html.TextBoxFor(model => model.CheckNumber, new { @Class = "CheckNumber", style = "width:100px" })
        }

        @Html.ValidationMessageFor(model => model.CheckNumber)
    </td>
    <td>
        @Html.HiddenFor(x => x.Delete, new { @class = "mark-for-delete" })
        @Html.LinkToRemoveNestedFormUpdateCounter("Remove", "tr.ClassAttendee", "input.mark-for-delete")
    </td>
</tr>

最後に紹介するのは、AJAX 呼び出しのサーバー側コードです。

public JsonResult GetAll()
    {
        var customers = customerRepository
            .All
            .Select(p => new
            {
                p.ID ,
                p.CustomerName
            })
            .OrderBy(o => o.CustomerName);
        return Json(customers, JsonRequestBehavior.AllowGet);
    }
4

2 に答える 2

0

私はこれをテストしていませんが、次のようなことができますか:

$(document).ready(function () {
    $.getJSON('@Url.Action("GetAll", "Customers")', function (customers) {
        var customerSelect = $('.Customers');
        customerSelect.empty();
        customerSelect.append('<option value="0">Choose Customer...</option>');
        $.each(customers, function (index, customer) {

            var option=$('<option/>', {
                value: customer.ID,
                text: customer.CustomerName
            });
            if(customer.ID=='@(Model.CustomerEmailID)')
                 $(option).attr("selected","selected");

            customerSelect.append(option);

        });
    });
});

アップデート

選択したIDを親の属性として追加できる場合<td>:

<td data-id="@(Model.CustomerEmailID)">    
    @Html.DropDownListFor(
        x => x.CustomerEmailID,
        Enumerable.Empty<SelectListItem>(),
        "Choose Attendee...",
                          new { @Class = "Contact", style = "width:220px" }
    )
    @Html.ValidationMessageFor(model => model.CustomerEmailID)
</td>

あなたはこれを行うことができます:

$(document).ready(function () {
    $.getJSON('@Url.Action("GetAll", "Customers")', function (customers) {
        var customerSelect = $('.Customers');
        customerSelect.empty();
        customerSelect.append('<option value="0">Choose Customer...</option>');
        $.each(customers, function (index, customer) {

            var option=$('<option/>', {
                value: customer.ID,
                text: customer.CustomerName
            });
            if(customer.ID==$(this).parent().attr("data-id"))
                 $(option).attr("selected","selected");

            customerSelect.append(option);

        });
    });
});
于 2012-12-13T20:41:30.483 に答える
0

そのため、ページをロードするときにエディターを使用しないことで、これを機能させることができました。代わりに、テーブルに以下のコードを入力します

<table id="Attendees" class="table-gridview">
        <thead>
            <tr>
                <th style="width:320px">
                    Customer
                </th>
                <th style="width:250px">
                    Attendee
                </th>
                <th>
                    Attended
                </th>
                <th>
                    Paid
                </th>
                <th style="width:120px">
                    Check Number
                </th>
                <th>

                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Attendees)
            {
              <tr class="ClassAttendee">
                <td>
                    @Html.HiddenFor(model => item.ID)
                    @Html.HiddenFor(model => item.ClassID)

                    @Html.DropDownList("Customers", ((IEnumerable<TRIOSoftware.Domain.Entities.Customer>)ViewBag.PossibleCustomers).Select(option => new SelectListItem
                   {
                       Text = (option == null ? "None" : option.CustomerName),
                       Value = option.ID.ToString(),
                       Selected = (Model != null) && (option.ID == item.CustomerEmail.CustomerID)
                   }),"Choose Customer...", new { @Class = "Customers", style = "width:300px" })
                </td>
                <td> 
                     @Html.DropDownListFor(model => item.CustomerEmailID, ((IEnumerable<TRIOSoftware.Domain.Entities.CustomerEmail>)ViewBag.PossibleContacts).Where(o => o.CustomerID == item.CustomerEmail.CustomerID).Select(option => new SelectListItem
                    {
                        Text = (option == null ? "None" : option.Name),
                        Value = option.ID.ToString(),
                        Selected = (Model != null) && (option.ID == item.CustomerEmailID)
                    }), "Choose Attendee...")   
                    @*@Html.DropDownListFor(model => item.CustomerEmailID, Enumerable.Empty<SelectListItem>(), "Choose Attendee...", new { @Class = "Contact", style = "width:220px" })*@
                    @Html.ValidationMessageFor(model => item.CustomerEmailID)
                </td>
                <td>    
                    @Html.CheckBoxFor(model => item.Attended)
                    @Html.ValidationMessageFor(model => item.Attended)
                </td>
                <td>    
                    @Html.CheckBoxFor(model => item.FeePaid, new { @Class = "FeePaid" })
                    @Html.ValidationMessageFor(model => item.FeePaid)
                </td>
                <td>    
                    @if (item.FeePaid != true)
                    {
                        @Html.TextBoxFor(model => item.CheckNumber, new { @Class = "CheckNumber", disabled = "true", style = "width:100px" })
                    }
                    else
                    {
                        @Html.TextBoxFor(model => item.CheckNumber, new { @Class = "CheckNumber", style = "width:100px" })
                    }

                    @Html.ValidationMessageFor(model => item.CheckNumber)
                </td>
                <td>
                    @Html.HiddenFor(x => item.Delete, new { @class = "mark-for-delete" })
                    @Html.LinkToRemoveNestedFormUpdateCounter("Remove", "tr.ClassAttendee", "input.mark-for-delete")
                </td>
            </tr>
            }
        </tbody>
    </table>

基本的に、テンプレート コードをビューに移動し、ドロップ ダウンに AJAX を入力する代わりに、ビューに送信するデータを最初のドロップ ダウンに入力します。

質問を少し開いたままにして、誰かがより良い答えを思いつくかどうかを確認します.

編集 - - - - - - - - - - - - - - - - - - - - - - - - - ------------------------------

このソリューションで値をコントローラーに渡して保存することに問題がありました。これを機能させる方法が他に見つからなかったので、これをビューのドキュメント準備機能に追加しました

 $("#Attendees tr").each(function (index) {
        $(this).find("input, select, span").each(function (indx, element) {
            if ($(element).attr('name') !== undefined) {
                var name = $(element).attr('name').replace("item", "Attendees[" + (index - 1) + "]");
                $(element).attr('name', name);
            } else {
                // attribute does not exist
            }

            if ($(element).attr('id') !== undefined) {
                var id = $(element).attr('id').replace("item", "Attendees_" + (index - 1) + "_");
                $(element).attr('id', id);
            } else {
                // attribute does not exist
            }

            if ($(element).attr('data-valmasg-for') !== undefined) {
                var dataval = $(element).attr('data-valmasg-for').replace("item", "Attendees[" + (index - 1) + "]");
                $(element).attr('data-valmasg-for', dataval);
            } else {
                // attribute does not exist
            }
        });


    });

基本的に、アイテム ID と名前を適切な名前に置き換えて、データをコントローラーに戻します。ちょっとしたハックですが、うまくいくので投稿したいと思います。

于 2012-12-13T20:36:54.703 に答える