基于Dropdown Parent的AJAX Fill Dropdown

时间:2015-10-10 02:41:08

标签: javascript jquery ajax asp.net-mvc-5

我想知道我的剧本有什么问题,它没有根据国家获得城市的价值,请看我的代码:

控制器:酒店

private ActionResult FillCity(int countryid)
{
    var cities = db.cities.Where(c => c.country_id == countryid);
    return Json(cities, JsonRequestBehavior.AllowGet);
}

的Jquery / AJAX

<script>
    function FillCity() {
        var countryid = $('#Country').val();
        $.ajax({
            url: '@Url.Action("FillCity")',
            type: "GET",
            dataType: "JSON",
            data: { countryid: countryid },
            success: function (cities) {
                $("#City").html(""); 
                $.each(cities, function (i, city) {
                    $("#City").append(
                        $('<option></option>').val(city.id).html(city.name));
                });
            }
        });
    }
</script>

查看

<div class="form-horizontal">
    <div class="form-group">
        @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.Country, new SelectList(ViewBag.CountryList, "id", "country_name"), "Select Country", htmlAttributes: new { @class = "form-control", @onchange = "FillCity()" })
            @Html.ValidationMessageFor(m => m.Country, "", new { @class = "text-danger" })
        </div>
    </div>
</div>
<div class="form-horizontal">
    <div class="form-group">
        @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.City, new SelectList(Enumerable.Empty<SelectListItem>(), "id", "name"), "Select City", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

我正在检查控制台,似乎网址是正确的enter image description here

1 个答案:

答案 0 :(得分:1)

您的方法被标记为私有,因此永远不会被命中。将其更改为

public ActionResult FillCity(int countryid)
{
    var cities = db.cities.Where(c => c.country_id == countryid).Select(c => new
    {
        id = c.id,
        name = c.name
    };
    return Json(cities, JsonRequestBehavior.AllowGet);
}

附注:如果typeof City包含的idname属性超过了您需要生成的选项(因为它至少包含country_id),您应该修改查询以返回仅包含视图中所需属性的匿名对象的集合