在MVC中加载2下拉列表的更好方法
我的控制器方法:
public ActionResult Index(){ var states = GetStates(); var cities = Enumerable.Empty<SelectListItem>(); ViewBag.States = states; ViewBag.Cities = cities;}private IEnumerable<SelectListItem> GetStates(){ using (var db = new DataEntities()) { return db.States.Select(d => new SelectListItem { Text = d.StateName, Value =d.Id.ToString() }); }}[HttpGet]public ActionResult GetCities(int id){ using (var db = new DataEntities()) { var data = db.Cities.Where(d=>d.StateId==id).Select(d => new { Text = d.CityName, Value = d.Id }).ToList(); return Json(data, JsonRequestBehavior.AllowGet); }}
我的观点:
IEnumerable<SelectListItem> States = ViewBag.States;IEnumerable<SelectListItem> Cities = ViewBag.Cities; @Html.DropDownList("State", States, "Select State", new { onchange="loadCities(this)"})@Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity"})function loadCities(obj) { $.ajax({ url: "/Home/GetCities", data: { id: $(obj).val() }, contentType:"application/json", success:function(responce){ var html = '<option value="0">Select City</option>'; $(responce).each(function () { html += '<option value="'+this.Value+'">'+this.Text+'</option>' }); $("#ddlCity").html(html); } }); }
芜湖不芜
相关分类