MVC三级下拉菜单

控制器端代码:

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)//提交与定位不一定一样
        {
            List<Productor> listProd = new ProductorDA().Select();//每次提交都是正确的
            ViewBag.Prods = new SelectList(listProd, "Prod_Code", "Prod_Name", prod);

            List<Brand> 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<Car> listCar = new CarDA().SelectByBrand(b);
            ViewBag.Cars = new SelectList(listCar, "Code", "Name",car);
            return View();
        }

        

        [HttpGet]
        public ActionResult Index()
        {
            List<Productor> listProd = new ProductorDA().Select();
            ViewBag.Prods = new SelectList(listProd, "Prod_Code", "Prod_Name", "p001");

            List<Brand> listBrand = new BrandDA().SelectByProd("p001");
            ViewBag.Brands = new SelectList(listBrand, "Brand_Code", "Brand_Name");

            List<Car> listCar = new CarDA().SelectByBrand("b001");
            ViewBag.Cars = new SelectList(listCar, "Code", "Name");
            return View();
        }
    }
}

视图端代码:

@using MvcApplication8.Models;
@model List<MvcApplication8.Models.Car>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @using(Html.BeginForm("Index","Cars", FormMethod.Post))
        {
        @Html.DropDownList("prod", ViewBag.Prods as SelectList,new { onchange="document.forms[0].submit();"})
        @Html.DropDownList("brand",ViewBag.Brands as SelectList,new { onchange="document.forms[0].submit();"})
        @Html.DropDownList("car",ViewBag.Cars as SelectList)
        }



        
    </div>
</body>
</html>

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 List<Car> Select()
        {
            return _Context.Car.ToList();
        }
        public List<Car> SelectByBrand(string brandCode)
        {
            var query = _Context.Car.Where(p => p.Brand == brandCode);
            return query.ToList();
        }
    }
}

 

posted @ 2015-07-15 18:15  Yusarin  阅读(531)  评论(0编辑  收藏  举报