在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);
}
});
}
3 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
function loadCities(obj) { $.getJSON("/Home/GetCities", function (data) { var html = '<option value="0">Select City</option>'; $(data).each(function () { html += '<option value="'+this.Value+'">'+this.Text+'</option>' }); $("#ddlCity").html(html); });}
- 3 回答
- 0 关注
- 481 浏览
添加回答
举报
0/150
提交
取消