控制器端代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcApplication8.Models;namespace MvcApplication8.Controllers{ public class CarsController : Controller { // // GET: /Cars/ public ActionResult Index(string prod, string brand, string car)//提交与定位不一定一样 { ListlistProd = new ProductorDA().Select();//每次提交都是正确的 ViewBag.Prods = new SelectList(listProd, "Prod_Code", "Prod_Name", prod); List listBrand = new BrandDA().SelectByProd(prod);//提交时prod提交也是正确的 ViewBag.Brands = new SelectList(listBrand, "Brand_Code", "Brand_Name",brand);//列表,Value值,Text值 var b = listBrand.Exists(p =>p.Brand_Code == brand)?brand:listBrand[0].Brand_Code; //brand提交的不一定是正确的提交,选prod时brand提交是错误的,选brand时brand提交是正确的 List listCar = new CarDA().SelectByBrand(b); ViewBag.Cars = new SelectList(listCar, "Code", "Name",car); return View(); } [HttpGet] public ActionResult Index() { List listProd = new ProductorDA().Select(); ViewBag.Prods = new SelectList(listProd, "Prod_Code", "Prod_Name", "p001"); List listBrand = new BrandDA().SelectByProd("p001"); ViewBag.Brands = new SelectList(listBrand, "Brand_Code", "Brand_Name"); List listCar = new CarDA().SelectByBrand("b001"); ViewBag.Cars = new SelectList(listCar, "Code", "Name"); return View(); } }}
视图端代码:
@using MvcApplication8.Models;@model List@{ Layout = null;} Index @using(Html.BeginForm("Index","Cars", FormMethod.Post)) { @Html.DropDownList("prod", ViewBag.Prods as SelectList,new { οnchange="document.forms[0].submit();"}) @Html.DropDownList("brand",ViewBag.Brands as SelectList,new { οnchange="document.forms[0].submit();"}) @Html.DropDownList("car",ViewBag.Cars as SelectList) }
Model层方法代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MvcApplication8.Models{ public class CarDA { private CarsDataContext _Context = new CarsDataContext(); public ListSelect() { return _Context.Car.ToList(); } public List SelectByBrand(string brandCode) { var query = _Context.Car.Where(p => p.Brand == brandCode); return query.ToList(); } }}