MVC 4 -级联下拉列表- Ajax JavaScript调用问题

MVC 4 - Cascading Dropdown Lists - Issue with Ajax JavaScript Call

本文关键字:JavaScript 调用 Ajax 问题 下拉列表 级联 MVC      更新时间:2023-09-26

我有一个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'的属性,因为每个值评估为假,即使其中一个值是真的。

我做错了什么吗?还是有更好的方法?

控制器代码如下:

[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);