繁体   English   中英

使用JQuery AJAX的MVC级联下拉菜单

[英]MVC Cascading Dropdown using JQuery AJAX

我有一个美国州的下拉列表。 当用户选择州时,将填充县/区的另一个下拉列表。 我正在从存储过程中提取信息以填充县下拉列表。 我的问题是,它正在为每个县返回对象Object,但我不知道该怎么做才能更正此问题。

这是控制器中的代码

public ActionResult FillCountyList(string State)
{
    Models.CountyList mod = new CountyList();
    mod.TheState = State;
    List<ListCountiesByState_Result> Counties = mod.ListCounties();
    return Json(Counties, JsonRequestBehavior.AllowGet);
}    

我也在控制器中尝试了以下操作,它还返回了一个列表,显示每个县的对象Object

public JsonResult FillCountyList(string State)
{
    IEnumerable<SelectListItem> Counties = db.ListCountiesByState(State).Select(c => new SelectListItem {
            Value = c.County,
            Text = c.County
    }).ToList();
    return Json(Counties, JsonRequestBehavior.AllowGet);
}

这是视图中的jQuery代码

$('#State').change(function () {
    var stateid = $('#State').val();
    $.ajax({
        url: '/Profile/BackgroundData/FillCountyList',
        type: 'GET',
        datatype: 'JSON',
        data: { State: stateid },
        success: function (result) {
            $('#CountyOrParrish').html('');
            $('#CountyOrParrish').append($('<option>Make Selection</option>'));
            $.each(result, function (i, item) {
                $('#CountyOrParrish').append($('<option></option>').text(item));
            });
        }
    });
});

您只需使用“。”即可在javascript上访问您的县属性。 分隔符,因为结果中的每个项目都是一个json对象:

$.each(result, function (i, item) {
           $('#CountyOrParrish').append($('<option></option>').text(item.CountyName));
        });

检查您的方法是否正确返回国家。 同时更改:

$('<option></option>').text(item));

至:

$('<option></option>').val(item.Value).html(item.Text));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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