Jquery 由AJAX填充的下拉列表未获得初始vlaue集

Jquery 由AJAX填充的下拉列表未获得初始vlaue集,jquery,asp.net-mvc,asp.net-mvc-3,Jquery,Asp.net Mvc,Asp.net Mvc 3,我有一个带有表的页面,其中有一个按钮可以动态添加行,还有一种删除行的方法。每行有两个级联的下拉列表。当创建一行时,我使用AJAX调用用值填充第一个下拉列表。在这个下拉列表的更改事件中,我执行另一个AJAX调用来填充第二个下拉列表。这一切都很好,但我的问题是,当我在屏幕上加载最初应该显示的数据时,我可以用AJAX调用填充下拉列表,但该值没有被选中,我猜是因为它是在绑定到我的模型后填充的。有没有办法正常处理这种情况?下面是my document ready函数中的代码 $(document).rea

我有一个带有表的页面,其中有一个按钮可以动态添加行,还有一种删除行的方法。每行有两个级联的下拉列表。当创建一行时,我使用AJAX调用用值填充第一个下拉列表。在这个下拉列表的更改事件中,我执行另一个AJAX调用来填充第二个下拉列表。这一切都很好,但我的问题是,当我在屏幕上加载最初应该显示的数据时,我可以用AJAX调用填充下拉列表,但该值没有被选中,我猜是因为它是在绑定到我的模型后填充的。有没有办法正常处理这种情况?下面是my document ready函数中的代码

$(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
            }));
        });
    });
});

因此,我在加载页面时没有使用editorfor,所以我成功地实现了这一点。现在,我用下面的代码填充该表

<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>

基本上,我用正确的名称替换项目ID和名称,以便将数据返回控制器。这有点像黑客,但确实有效,所以我想发布它。

我还没有测试过这个,但你能做一些类似的事情吗:

$(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);

        });
    });
});
$(文档).ready(函数(){
$.getJSON('@Url.Action(“GetAll”,“Customers”)),函数(Customers){
var customerSelect=$('.Customers');
customerSelect.empty();
customerSelect.append('choosecuster…');
$。每个(客户、功能(索引、客户){
var选项=$(''{
值:customer.ID,
文本:customer.CustomerName
});
if(customer.ID='@(Model.CustomerEmailID)')
$(选项).attr(“选定”、“选定”);
customerSelect.append(选项);
});
});
});
更新

如果可以将所选id添加为父项的属性,如:

<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>

@Html.DropDownListFor(
x=>x.CustomerEmailID,
Enumerable.Empty(),
“选择与会者…”,
新建{@Class=“Contact”,style=“width:220px”}
)
@Html.ValidationMessageFor(model=>model.CustomerEmailID)
您可以这样做:

$(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);

        });
    });
});
$(文档).ready(函数(){
$.getJSON('@Url.Action(“GetAll”,“Customers”)),函数(Customers){
var customerSelect=$('.Customers');
customerSelect.empty();
customerSelect.append('choosecuster…');
$。每个(客户、功能(索引、客户){
var选项=$(''{
值:customer.ID,
文本:customer.CustomerName
});
if(customer.ID=$(this.parent().attr(“数据ID”))
$(选项).attr(“选定”、“选定”);
customerSelect.append(选项);
});
});
});

您是否尝试过调试控制器中的Json?我不太明白您的建议?我没有逐行浏览,但当页面出现保存的行项目时,我看到的是第一个组合框中填充了值,但保存的组合框未选中,它位于第一个值上。很抱歉,我以为你的意思是你不确定是否进入了你的函数。您是否将保存的选定Id隐藏在页面中?我不确定是模型Id还是ClassId,所以我想我会问。是EditorTemplate中显示的Model.Id是子项的键,并且我确实为视图中的每一行隐藏了它。我的解决方案的问题是,我的表中可以有任意数量的行,因此它将绑定到@(Model.customeremaild)它将是@(型号..CustomerEmailID)仍然没有对此进行任何测试,但我用另一种可能的解决方案更新了我的答案。你看过了吗,@DaveWade?我确实尝试过,但在尝试在编辑器模板上添加数据id时出错。即使我将CustomerEmail对象传递到视图中时模型中有CustomerEmail对象,但编辑器模板在我试图将CustomerMail.CustomerID的数据id添加到其中一个下拉列表中,但失败了。因此,CustomerID在数据库中为空,或者只是没有在模型中填充?结果证明,这个答案比我想象的更糟。当我使用编辑器teplate显示数据时,我自动将数据放入其中,从而允许我的模型自动获取此信息claly在一篇文章中,现在使用foreach循环,数据被项目替换,这是我在foreach循环中使用的,所以现在当我让bakc发布时,我没有与会者信息。通过编辑此答案,解决方案可以工作。我更喜欢@Michael_B的解决方案,因为它看起来不像是一个黑客,但我无法获得我的客户的数据idr在我的编辑模板中
 $("#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
            }
        });


    });
$(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);

        });
    });
});
<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);

        });
    });
});