本例使用的是EF first code操作数据库。
一、准备数据库
级联下拉列表框,比较经典的就是省市数据表,在Model里同时创建三个类:province.cs、city.cs和dropContext.cs
1、province.cs
[Table("province")]public class province{[Key]public int proID { get; set; }public string proName { get; set; }public virtual IEnumerablecity { get; set; }}
2、city.cs
public class city{public int cityID { set; get; }public string cityName { set; get; }public int proID { set; get; }public virtual province pronvince { set; get; }}
3、dropContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; //必须添加 using System.Data.Entity; //必须添加 using System.Data.Entity.ModelConfiguration.Conventions;namespace dropdown.Models {public class dropContext : DbContext{public dropContext(): base("name=constr"){}public DbSetcity { get; set; }public DbSet province { get; set; }protected override void OnModelCreating(DbModelBuilder modelBuilder){//base.OnModelCreating(modelBuilder);modelBuilder.Conventions.Remove ();}}}
二、控制器
新建dropController控制器
public class dropController : Controller{private dropContext db = new dropContext();public ActionResult Index(){//生成省份列表ViewBag.pro = new SelectList(db.province, "proID", "proName");//生成城市列表ViewBag.city = new SelectList(db.city, "cityID", "cityName");return View();}public ActionResult getData(int ID){if(Request.IsAjaxRequest()) //判断是否使用ajax {var q = from c in db.citywhere c.proID == IDselect new { c.cityID, c.cityName }; //不能查询出c.proID,否则会出错return Json(q,JsonRequestBehavior.AllowGet); //返回json数据 }return View();}}
三、视图
添加视图Index.cshtml
下拉列表
@Html.DropDownList("pro", "请选择") @Html.DropDownList("city","请选择")
利用JQuery ajax将参数ID传递给getData方法进行处理,getData方法处理完后返回JSON序列,将此序列绑定到城市下拉框里即可。