【问题标题】:MVC 4 - Cascading Dropdown Lists - Issue with Ajax JavaScript CallMVC 4 - 级联下拉列表 - Ajax JavaScript 调用问题
【发布时间】:2013-03-31 08:56:44
【问题描述】:

我有一个 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。问题是“选定”似乎不是“数据”的属性,因为每个值的计算结果都为假,即使其中一个值为真。

我做错了吗?还是有更好的方法来做到这一点?

以下是控制器代码:

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

【问题讨论】:

  • 你能显示控制器操作返回的内容吗?
  • @nuhusky2003 - 刚刚添加。谢谢。
  • SelectLists 没有 selected 属性。他们确实有一个 SelectedValue 属性

标签: javascript jquery asp.net-mvc html asp.net-mvc-4


【解决方案1】:

试试这个(将 modelId 添加到 SelectList 的构造函数中,并删除 foreach 块):

// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);

return Json(returnList);

【讨论】:

  • 谢谢。我应该注意到控制这个的参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 2011-10-05
  • 1970-01-01
相关资源
最近更新 更多