使用 Json 和 Jquery 的 Asp.net MVC4 中的级联下拉列表不填充

Posted

技术标签:

【中文标题】使用 Json 和 Jquery 的 Asp.net MVC4 中的级联下拉列表不填充【英文标题】:Cascading Dropdown List in Asp.net MVC4 using Json and Jquery not Populate 【发布时间】:2015-03-09 06:11:28 【问题描述】:

两周以来,我一直在尝试创建一个包含 3 个下拉列表的 ASP.NET MVC 4 应用程序。 它们是 Country、State 和 City 。 我关注this article

我从数据库调用的这些数据库列表详细信息

连接字符串:

<connectionStrings>
    <add name="CACD_Con" connectionString="metadata=res://*/Models.Project_Name.csdl|res://*/Models.Project_Name.ssdl|res://*/Models.Project_Name.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.0.000;initial catalog=CACD;persist security info=True;user id=000;password=000000000;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

控制器类:

 public class CacadingController : Controller

    private ProjectContext db = new ProjectContext();

    public ActionResult Index()
    
        ViewBag.CountryId = new SelectList(db.Countrys, "CountryId", "CountryName");
        return View();
    

    public JsonResult StateList(int Id)
    
        var state = from s in db.States
                       where s.CountryId == Id
                       select s;
        return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
    

    public JsonResult Citylist(int id)
    
        var city = from c in db.Citys
                   where c.StateId == id
                   select c;
        return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
    

    public IList<State> Getstate(int CountryId)
    
        return db.States.Where(m => m.CountryId == CountryId).ToList();
    

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult LoadClassesByCountryId(string CountryName)
    
        var stateList = this.Getstate(Convert.ToInt32(CountryName));
        var stateData = stateList.Select(m => new SelectListItem()
        
            Text = m.StateName,
            Value = m.CountryId.ToString(),
        );
        return Json(stateData, JsonRequestBehavior.AllowGet);
    


模型类:

public partial class ProjectContext : DbContext
    
        public ProjectContext()
            : base("CACD")
        
        

        public DbSet<Country> Countrys  get; set; 
        public DbSet<State> States  get; set; 
        public DbSet<City> Citys  get; set; 

        

    public class Country
    
        [Key]
        public int CountryId  get; set; 
        public string CountryName  get; set; 

        public virtual ICollection<State> States  get; set; 
    


    public class State
    
        [Key]
        public int StateId  get; set; 
        public string StateName  get; set; 
        [ForeignKey("Country")]
        public int CountryId  get; set; 

        public virtual Country Country  get; set; 
        public virtual ICollection<City> Citys  get; set; 
    

    public class City
    
        [Key]
        public int CityId  get; set; 
        public string CityName  get; set; 
        [ForeignKey("State")]
        public int StateId  get; set; 

        public virtual State State  get; set; 
    

查看文件(cshtml)

@model Project_Name.Models.ProjectContext

@using (Html.BeginForm())

@Html.DropDownList("Country", ViewBag.CountryId as SelectList, "Select a Country", new  id="Country" )<br />
    <select id="State" name="state"></select><br />
    <select id="city" name="City"></select><br />


@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(function () 
        $('#Country').change(function () 
            $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) 
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) 
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                );
                $('#State').html(items);
            );
        );

        $('#State').change(function () 
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) 
                var items = '<option>Select a City</option>';
                $.each(data, function (i, city) 
                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                );
                $('#city').html(items);
            );
        );
    );
</script>

但是下拉菜单没有显示数据库中的任何数据,如果你能告诉我正确的路径真的很感激

【问题讨论】:

什么不起作用?是否填充了第一个下拉列表(国家/地区)? 并非上述任何一个 dropdwon 都不会填充任何内容 那么您需要调试您的代码 - db.Countrys 是否返回任何有效数据? (你不需要在视图中@model AFFEMS2_HEC.Models.ProjectContext - 那不是你的模型!) 它编译良好,没有任何错误,但是 db.Countrys 没有返回任何数据 【参考方案1】:
   where  cityList is list containing city model

var result = from item in cityList
                                 select new
                                 
                                     value = item.CityId,
                                     text = item.Name
                                 ;
                    return Json(result, JsonRequestBehavior.AllowGet);

and in script add
 $('#State').change(function () 
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) 
                 var items = [];
                items.push("<option>Select City</option>");
                $.each(data, function () 
                    items.push("<option value=" + this.value + ">" + this.text + "</option>");
                );
                $(city).html(items.join(' '));
            );
        );

do same for state

【讨论】:

【参考方案2】:

我在我的项目中使用了第一个,但没有将信息保存在数据库中.. 保存我在视图中所做的国家:

 @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryId as SelectList, "Select a Country", new  id = "Country", @class = "form-control" )<br />

但下一个不保存,但如果我像上面那样更改它,脚本将不起作用 任何帮助...

**<select id="StateId" name="state" class="form-control"></select><br />
<select id="CityId" name="City" class="form-control"></select><br />**

脚本 **

@section Scripts 
        @Scripts.Render("~/bundles/jqueryval")
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/jscript">
        $(function () 
            $('#Country').change(function () 
                $.getJSON('/AddressBooks/StateList/' + $('#Country').val(), function (data) 
                    var items = '<option>Select a State</option>';
                    $.each(data, function (i, state) 
                        items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                    );
                    $('#StateId').html(items);
                    $('#CityId').html(null);
                );
            );

            $('#StateId').change(function () 
                $.getJSON('/AddressBooks/Citylist/' + $('#StateId').val(), function (data) 
                    var items = '<option>Select a City</option>';
                    $.each(data, function (i, city) 
                        items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                    );
                    $('#CityId').html(items);
                );
            );
        );
        </script>

**

在控制器上

public ActionResult Create()
        

            ViewBag.CustomerId = new SelectList(db.Customers, "Id", "FullName");
            ViewBag.CountryId= new SelectList(db.Countries, "CountryId", "CountryName");
            return View();
        
        public JsonResult StateList(int Id)
        
            var state = from s in db.States
                        where s.CountryId == Id
                        select s;

            return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
        

        public JsonResult Citylist(int id)
        
            var city = from c in db.Cities
                       where c.StateId == id
                       select c;

            return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
        

        public IList<State> Getstate(int CountryId)
        
            return db.States.Where(m => m.CountryId == CountryId).ToList();
        
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByCountryId(string CountryName)
        
            var stateList = this.Getstate(Convert.ToInt32(CountryName));
            var stateData = stateList.Select(m => new SelectListItem()
            
                Text = m.StateName,
                Value = m.CountryId.ToString(),
            );
            return Json(stateData, JsonRequestBehavior.AllowGet);
        

【讨论】:

【参考方案3】:

我解决了问题

@Html.DropDownList("CountryId", null, htmlAttributes: new  id = "Country", @class = "form-control" )

@Html.DropDownListFor(model => model.StateId, new SelectList(Enumerable.Empty<selectlistitem>(), "StateId", "StateName"), "Select State", new  id = "StateId", @class = "form-control" )

@Html.DropDownListFor(model => model.CityId, new SelectList(Enumerable.Empty<selectlistitem>(), "CityId", "CityName"),"Select city",new  id = "CityId", @class = "form-control" )

json

@section Scripts 
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () 
$('#Country').change(function () 
$('#StateId').html(null)
$('#CityId').html(null);
$.getJSON('/AddressBooks/StateList/' + $('#Country').val(), function (data)        
$.each(data, function (i, state) 
$("#StateId").append(
"<option value="" + state.Value + "">" + state.Text + "</option>")
);
);
);

$('#StateId').change(function () 
$('#CityId').html(null);
$.getJSON('/AddressBooks/Citylist/' + $('#StateId').val(), function (data) 
$.each(data, function (i, city) 
$("#CityId").append(
"<option value="" + city.Value + "">" + city.Text + "</option>");

);
);
);
);
</script>

【讨论】:

以上是关于使用 Json 和 Jquery 的 Asp.net MVC4 中的级联下拉列表不填充的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NE网站发布注意事项

win7+iis7.5+asp.net下 CS0016: 未能写入输出文件“c:WindowsMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NE

ASP.NET 核心标识。使用 ApplicationDbContext 和 UserManager。他们是不是共享上下文?

在 WPF、Silverlight 和 ASP.NET 之间共享一个公共 DAL

使用json 和jQuery制作级联dropdownlist

jQuery Json数据格式排版高亮插件json-viewer.js的使用