首页 > 解决方案 > Asp.net MVC 中的三个表级联下拉列表

问题描述

我想在 Asp.Net MVC 中有一个级联下拉列表。我已经设法用两张表做到了CountryState现在我想添加City

public class Country
{
    [Key]
    public int cId { get; set; }
    public string cName { get; set; }
    public ICollection<State> state { get; set; }
}

public class State
{
    [Key]
    public int sId { get; set; }
    public string sname { get; set; }
    public int cId { get; set; }
    public Country country { get; set; }
}


//Get list of States

public JsonResult GetStateList(int cId)
{
    db.Configuration.ProxyCreationEnabled = false;
    List<State> listState = db.States.Where(x => x.cId == cId).ToList();

    return Json(listState,JsonRequestBehavior.AllowGet);
}

//Script that invokes the Method


$(document).ready(function () {
    $("#cId").change(function () {
        $.get("/Home/GetStateList", { cId: $("#cId").val() }, function (data) {
            $("#sId").empty();
            $.each(data, function (index, row) {
                $("#sId").append("<option value= '"+row.sId+"'>"+ row.sname+"</option>")
            });
        });
    })
});

标签: javascriptc#jsonasp.net-mvc

解决方案


好吧,只需添加以下内容:

public class City
{
    [Key]
    public int cityId { get; set; }
    public string cityName { get; set; }
    public int sId { get; set; } // stateId
    public State state { get; set; }
}

public JsonResult GetCityList(int sId)
{
    db.Configuration.ProxyCreationEnabled = false;
    List<City> listCity = db.Cities.Where(x => x.sId == sId).ToList();

    return Json(listCity,JsonRequestBehavior.AllowGet);
}

$(document).ready(function () {
    $("#sId").change(function () {
        $.get("/Home/GetCityList", { sId: $("#sId").val() }, function (data) {
            $("#cityId").empty();
            $.each(data, function (index, row) {
                $("#cityId").append("<option value= '"+row.cityId+"'>"+ row.cityName+"</option>")
            });
        });
    })
});

推荐阅读