繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM