我有一个 MVC 4 应用程序,其 View 包含两个下拉列表。用户在第一个下拉列表中选择一个值,然后进行 Ajax 调用以根据第一个下拉列表的内容填充第二个下拉列表。
我的 JavaScript 代码如下所示,当用户在第一个下拉列表中选择一个项目时,该代码将被调用:
function GetAutoModel(_manufacturerId) {
var autoSellerListingId = document.getElementById("AutoSellerListingId").value;
$.ajax({
url: "/AutoSellerListing/GetAutoModel/",
data: { manufacturerId: _manufacturerId, autoSellerListingId: autoSellerListingId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>-- Select --</option>";
for (var x = 0; x < data.length; x++) {
**if (data[x].Selected) {**
markup += "<option selected='selected' value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
else
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$('#autoModel').html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
Ajax 调用工作正常。但是,第二个下拉列表返回的数据包含选定的项目,我正在尝试检测选定的项目(通过“if”语句),并适本地呈现 HTML。问题是“Selected”似乎不是“data”的属性,因为每个值的计算结果都是 false,即使其中一个值是 true。
我做错了什么吗?或者有更好的方法来做到这一点吗?
以下是 Controller 代码:
[HttpPost]
public ActionResult GetAutoModel(int manufacturerId, int autoSellerListingId)
{
int modelId = 0;
// Get all the models associated with the target manufacturer
List<AutoModel> modelList = this._AutoLogic.GetModelListByManufacturer(manufacturerId);
// If this is an existing listing, get the auto model Id value the seller selected.
if (autoSellerListingId > 0)
modelId = this._systemLogic.GetItem<AutoSellerListing>(row => row.AutoSellerListingId == autoSellerListingId).AutoModel.AutoModelId;
// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description");
// Now find the selected model in the list and set it to selected.
foreach (var item in returnList)
{
if (item.Value == modelId.ToString())
item.Selected = true;
}
return Json(returnList);
}
最佳答案
试试这个(将 modelId 添加到 SelectList 的构造函数中,并删除 foreach block ):
// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);
return Json(returnList);
关于javascript - MVC 4 - 级联下拉列表 - Ajax JavaScript 调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15719399/