首页 > 解决方案 > 级联下拉列表不会从数据库加载(MVC、JSON、C#)

问题描述

全部 -

我是 MVC/Javascript 的新手,并尝试了多个教程,了解如何在 MVC 视图上获得适用于州和市的级联下拉列表。我最近的尝试我正在使用这个示例

州从数据库中填充,但城市是一个空白下拉列表,大约有 10 个空白区域。不管我选择什么状态。我错过了什么?感谢您的关注和建议/反馈!

这是数据库表信息:

Regions (contains states): Id (PK Int), Name (Varchar(255) state/regionname), CountryId (Int) Cities (Contains city): Id (PK Int), Name (Varchar(255) state/name), RegionID(int,指向区域表的链接)

这是视图模型:

public class UserAds
{
    public int addId { get; set; }
    public int userCreatedAcctId { get; set; }
    public string userForAccEmail { get; set; }
    public string photoFileLocation { get; set; }
    public string addTitle { get; set; }
    public string addDesc { get; set; }
    public string addPersonalityTraits { get; set; }
    public string addHobbies { get; set;}
    [Required]
    [Display(Name = "State / Region")]
    public int stateId { get; set; }
    [Required]
    [Display(Name = "City")]
    public int cityId { get; set; }
}

这是控制器:

        [HttpGet]
    public ActionResult CreateAd()
    {
        List<Region> stateList = db.Regions.ToList();
        ViewBag.StateList = new SelectList(stateList, "Id", "Name");
        return View();
    }

    public JsonResult GetCitiesList(int StateId)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<City> CityList = db.Cities.Where(x => x.RegionId == StateId).ToList();
        return Json(CityList, JsonRequestBehavior.AllowGet);

    }

风景:

<div class="container">
<div class="form-group">
    @if (ViewBag.StateList != null)
    {
        @Html.DropDownListFor(model => model.stateId, ViewBag.StateList as SelectList, "--Select State--", new { @class = "form-control" })
    }
</div>
<div class="form-group">
    @Html.DropDownListFor(model => model.cityId, new SelectList(" "), "--Select City--", new { @class = "form-control" })
</div>

javascript

<script>
$(document).ready(function () {
    $("#stateId").change(function () {
        $.get("GetCitiesList", { StateId: $("#stateId").val() }, function (data) {
            $("#cityId").empty();
            $.each(data, function (index, row) {
                $("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")
            });
        });
    })
});

IE 中的 Javascript 调试器

标签: javascriptjsonasp.net-mvccascadingdropdown

解决方案


在下面的行中,您在后面缺少一个单引号value=

$("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")

理想情况下,它应该如下所示 -

$("#cityId").append("<option value='" + row.Id + "'>" + row.Name + "</option>")

推荐阅读