我有一个带有级联下拉列表的视图的 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);
}
请注意控制器代码中调用的最后一个参数new SelectList()
(modelId)。这就是我希望在 Ajax 调用中创建选择对象后将所选值设置为的值。问题是我不知道如何在客户端访问这个值。一切正常,我只是不知道如何访问选定的值,然后设置它。