我有一个带有表格的页面,该表格带有一个按钮来动态添加行以及一种删除行的方法。每行有 2 个级联的下拉列表。创建行时,我使用 AJAX 调用来填充第一个下拉列表中的值。在此下拉列表的更改事件中,我执行另一个 AJAX 调用来填充第二个下拉列表。这一切都很好,但我的问题是,当我用最初应该显示的数据加载屏幕时,我可以用 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);
}