[英]MVC 4 - Cascading Dropdown Lists - Issue with Ajax JavaScript Call
我有一個MVC 4應用程序,其中包含兩個下拉列表。 用戶在第一個下拉列表中選擇一個值,然后進行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。
難道我做錯了什么? 或者有更好的方法嗎?
以下是控制器代碼:
[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塊):
// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);
return Json(returnList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.