Models结构
ProductorBF
public class ProductorBF { private MyDbDataContext Context = new MyDbDataContext(); public List<Productor> Select() { return Context.Productor.ToList(); } public Productor Select(string prod_code) { var query = Context.Productor.Where(c => c.Prod_Code == prod_code); if (query.Count() > 0) { return query.First(); } return null; }
BrandBF
public class BrandBF { private MyDbDataContext Context = new MyDbDataContext(); public List<Brand> Select() { return Context.Brand.ToList(); } public List<Brand> Select(string Prod_Code) { var query = Context.Brand.Where(c => c.Prod_Code == Prod_Code); if (query.Count() > 0) { return query.ToList(); } return null; } public bool SelectBool(string brandcode) { var query = Context.Brand.Where(p=>p.Brand_Code==brandcode); if (query.Count()>0) { return true; } return false; } }
CarBF
public class CarBF { private MyDbDataContext Context = new MyDbDataContext(); public List<Car> Select() { return Context.Car.ToList(); } public List<Car> Select(string Brand_Code) { var query = Context.Car.Where(c=>c.Brand==Brand_Code); if (query.Count()>0) { return query.ToList(); } return null; } }
控制器
public ActionResult Index() { List<Productor> listP = new ProductorBF().Select(); //参数:集合、列values值、显示的列、选取的显示值 SelectList listProd = new SelectList(listP,"Prod_Code","Prod_Name","p001"); List<Brand> listB = new BrandBF().Select(); SelectList listBrand = new SelectList(listB,"Brand_Code","Brand_Name"); ViewBag.Brands = listBrand; List<Car> listC = new CarBF().Select(); SelectList listCar = new SelectList(listC,"Code","Name"); ViewBag.Cars = listCar; return View(listProd); } [HttpPost] public ActionResult Index(string prod,string brand,string car) { //prod厂家编号,每次提交过来的编号都是正确的。改变厂家提交(改变第二级车系提交)过来的prod都是正确的 List<Productor> listP = new ProductorBF().Select(); SelectList listProd = new SelectList(listP,"Prod_Code","Prod_Name",prod); //根据正确的厂家编号prod查询出的车系也是正确的 //在下拉列表中定位车系,可以判断是否是改变了车系提交过来的数据。如果没有改变车系,提交, //brand是上一次的旧数据,如果改变车系提交,提交过来的brand是新选取的数据 List<Brand> listB = new BrandBF().Select(prod); var c = new BrandBF().SelectBool(brand) ? brand : listB[0].Brand_Code; SelectList listBrand = new SelectList(listB, "Brand_Code", "Brand_Name", c); ViewBag.Brands = listBrand; //与上面情况相同,页面没有操作车系的情况下,车辆的查询按上面新查出的车系编号查询 //页面操作改变车系的情况下,按提交过来的车系编号查询 var b = listB.Exists(p => p.Brand_Code == brand) ? brand : listB[0].Brand_Code; List<Car> listC = new CarBF().Select(b); SelectList listCar = new SelectList(listC,"Code","Name",car ); ViewBag.Cars = listCar; return View(listProd); }
Views
<div> @using(@Html.BeginForm("Index","Cars",FormMethod.Post)) { @Html.DropDownList("prod", Model, new { onchange = "document.forms[0].submit()" })@*js方法,值发生变化触发,效果==Html中第一个表单中的‘submit’提交*@ @Html.DropDownList("brand",ViewBag.Brands as SelectList, new { onchange="document.forms[0].submit()" }) @Html.DropDownList("car", ViewBag.Cars as SelectList) } </div>
效果
第一级厂家变化
第二级车系变化