下拉菜单填充另一个c#mvc json ajax

时间:2016-04-17 02:47:22

标签: c# jquery json ajax asp.net-mvc

以下是我的代码,我不确定我做错了什么?

Ajax json jquery代码

function FillCity() {
    var countryid = $("select[name$='.countryid']").val();     //<---- this is dynamic
    $.ajax({
        url: "Controller/FillMyCity",
        type: "POST",
        dataType: "json",           
        data: { country: countryid } ,           
        success: function (city) {
            $("select[name$='.cityid']").html(""); // <--- this is dynamic
            $.each(city, function (i, pp) {
                $("select[name$='.cityid']").append(
                    $('<option></option>').val(pp.cityid).html(pp.name));
            });               
        },
        error: function (err) {                
            alert(err);
        }
    });
}

控制器方法

public JsonResult FillMyCity(int country)
{

    var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
    {
        cityid = item.cityid,
        name = item.name
    }).AsQueryable();
    return Json(cities, JsonRequestBehavior.AllowGet);
}

查看

@Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { @class = "form-control countries", @id = "mycountry" + i + "", @onchange = "FillCity()" })
@Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { @class = "form-control cities", @id = "mycity" + i + "" })      

输出

EmployeeName  Country                       City
Jenny         ddl of countries              ddl of cities     
John          ddl of countries              ddl of cities

问题1:当我为Jenny选择国家时,Jenny + John的城市ddl都会被Jenny的国家城市填充,但它应该只适用于Jenny。当我为约翰选择国家时,城市ddl列表没有填充所以只有Jenny的作品,John没有

问题2:由于它是一个附加html的动态json jquery,我无法保存cities值,这是因为它是动态的并且不会出现在视图源中。

1 个答案:

答案 0 :(得分:0)

您对$("select[name$='.countryid']").val();的使用只会选择name属性以.countryid结尾的第一个元素的值。

此外,使用DropDownList("Country[" + i + "].countryid", ...)不是为集合生成控件的正确方法,它不太可能正确绑定到您的模型,但是您没有显示模型,因此无法修复,所以根据您当前的代码,您的视图应该是

<div class="container">
    @Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { @class = "form-control countries" })
    @Html.DropDownList("City[" + i + "].cityid", Enumerable.Empty<SelectListItem>(), new { @class = "form-control cities" })
</div>

和脚本

$('.countries').change(function() {
    var country = $(this).val();
    var cities = $(this).next('.cities'); // get the associated cities dropdownlist
    cities.empty(); // clear existing options
    $.ajax({
        url: '@Url.Action("FillMyCity")', // do not hard code url's
        type: "POST",
        dataType: "json",           
        data: { country: country } ,           
        success: function (data) {
            if (data) {
                cities.append($('<option></option>').val('').text('Select city'));
                $.each(data, function (index, item) {
                    cities.append($('<option</option>').val(item.cityid).html(item.name));
                });
             } else {
                 // oops
             }            
        },
        error: function (err) {                
            alert(err);
        }
    });
});

最后,返回一组匿名对象,其中仅包含视图中所需的数据,以避免发送不会使用的额外数据

public JsonResult FillMyCity(int country)
{
    // No need for .ToList()
    var cities = db.Cities.Where(x => x.countryid == country).Select(item => new
    {
        cityid = item.cityid,
        name = item.name
    });
    return Json(cities); // its a POST so no need for JsonRequestBehavior.AllowGet
}