asp.net MVC cascading dropdown lists

前端 未结 2 1858
礼貌的吻别
礼貌的吻别 2020-12-12 02:27

I\'m trying to create some cascading dropdown lists in asp.net. The lists are populating correctly on page load:

            
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 02:59

    Your drop down id is Region but in your success function you are using Regions

    Make this one small change and it will work.

    Controller:

    public class MyCountry
    {
        public int CountryCode { get; set; }
        public string Country { get; set; }
    }
    
    public class Region
    {
        public int CountryCode { get; set; }
        public string RegionName { get; set; }
    }
    
    public class ViewModel
    {
        public List Country { get; set; }
        public List Region { get; set; }
    }
    
    public class DropDownExampleController : Controller
    {
        public ActionResult Index()
        {
            var model = new ViewModel();
    
            var c1 = new MyCountry { Country = "South Africa", CountryCode = 1 };
            var c2 = new MyCountry { Country = "Russia", CountryCode = 2 };
    
            model.Country = new List { c1, c2 };
    
            var r1 = new Region { RegionName = "Gauteng", CountryCode = 1};
            var r2 = new Region { RegionName = "Western Cape", CountryCode = 1 };
            var r3 = new Region { RegionName = "Siberia", CountryCode = 2 };
    
            model.Region = new List { r1, r2,r3};
            return View(model);
        }
    
        [HttpPost]
        public JsonResult GetRegionsByCountryCode(string countryCode)
        {
            var r1 = new Region { RegionName = "Gauteng", CountryCode = 1 };
            var r2 = new Region { RegionName = "Western Cape", CountryCode = 1 };
            var r3 = new Region { RegionName = "Siberia", CountryCode = 2 };
    
            var regions = new List { r1, r2, r3 };
    
            var results = regions.Where(r => r.CountryCode == Int32.Parse(countryCode)).ToList();
    
            return Json(results);
        }
    }
    

    View:

    @model MVCTutorial.Controllers.ViewModel
    
    
    
    
    
    Country @Html.DropDownListFor(m => m.Country, new SelectList(Model.Country, "CountryCode", "Country"), "--Select--", new { @class = "form-control" })
    Region @Html.DropDownListFor(m => m.Region, new SelectList(Model.Region, "CountryCode", "RegionName"), "--Select--", new { @class = "form-control" })

提交回复
热议问题