我有一个带有级联下拉列表的View的MVC应用程序。在用户在第一个下拉列表中选择了值之后,我有以下Ajax调用来检索第二个下拉列表的数据:
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++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$('#ModelList').html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
调用以下控制器代码来提供Ajax调用数据:
[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 and return it
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);
return Json(returnList);
}
注意控制器代码(modelId)中new SelectList()
调用中的最后一个参数。这就是我希望在Ajax调用中创建select对象后将所选值设置为。问题是我不知道如何在客户端中访问此值。一切正常,我只是不知道如何访问所选值,然后设置它。
答案 0 :(得分:2)
问题是我不知道如何在客户端访问此值。
您可以查看客户端上的Selected
布尔属性:
if (data[x].Selected) {
markup += "<option value=" + data[x].Value + " selected=\"selected\">" + data[x].Text + "</option>";
} else {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}