【问题标题】:dropdown menu populate another c# mvc json ajax下拉菜单填充另一个 c# mvc json ajax
【发布时间】:2016-04-17 02:47:21
【问题描述】:

下面是我的代码,我不知道我做错了什么?

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's Country 的城市,但它应该只适用于 Jenny。当我为约翰选择国家时,城市 ddl 列表不会被填充所以只有珍妮的作品,约翰没有

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

【问题讨论】:

  • 您应该更具体地清除自己...您的确切问题是什么?
  • @Md.MostafizurRahman 我上面提到的问题是,当我为珍妮选择一个国家时,该国家的城市也会为约翰的城市的 ddl 填充?它应该只适用于珍妮。我说的另一个问题是无法将“城市”保存到数据库,因为它是动态的。谢谢

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


【解决方案1】:

您对$("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
}

【讨论】:

  • 感谢您的回复,但它不起作用,我得到 [object object]。还有关于 ddl “Country[” + i + “].countryid” 和 “City[” + i + “].cityid” 的名称。我这样做是因为我可以遍历每个单独选择的集合,它确实适用于国家,但不适用于职位。最后一件事,如何将所选位置选择回 json?非常感谢
  • 它确实有效。您没有正确使用代码。要查看级联下拉列表的工作示例,请参阅 this DotNetFiddle。您需要学习 mdoel 绑定到集合的基础知识 - 您使用 for 循环或 EditorTemplate 绑定到集合 - 请参阅 this answer 以获取示例
  • 感谢您的快速响应。模型绑定很好,它是我似乎无法通过的 [object object]。顺便说一句,我也无法使用 enumerable,因为我也遇到了这个错误:“system linq iqueryable anonymous type 1 does not contain a definition for enumerable”
  • 对不起,应该删除。不管您怎么想,您的模型绑定都无法正常工作。研究我链接的小提琴。
  • 你是什么意思不将html附加到位置var cities = $(this).next('.cities'); 将在您做出选择后立即获得下一个下拉菜单 - 带有class="cities" 的下拉菜单),因此它会将选项附加到该下拉菜单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多