MVC3学习:利用mvc3+ajax实现级联下拉列表框

本例使用的是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 IEnumerable<city> city { 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 DbSet<city> city { get; set; }

        public DbSet<province> province { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            //base.OnModelCreating(modelBuilder);

            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();



        }

    }



}

二、控制器

新建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.city

                        where c.proID == ID

                        select new { c.cityID, c.cityName }; //不能查询出c.proID,否则会出错

            return Json(q,JsonRequestBehavior.AllowGet); //返回json数据

            }

            return View();

        }

    }
View Code

三、视图

添加视图Index.cshtml

<script type="text/javascript">

    $(function () {

        $("#city").find("option").remove();

        $("#pro").change(function () {

            var pid = $(this).val();

            $("#city").find("option").remove();

            $.post("/drop/getData",{ID:pid},

            function(data)

               {

                 $.each(data,function(i,item)

                 {

                   $("<option></option>").val(item["cityID"]).text(item["cityName"]).appendTo($("#city"));

                 });

               });

        });

    });

    

</script>



<h2>下拉列表</h2>

@Html.DropDownList("pro", "请选择")

@Html.DropDownList("city","请选择")
View Code

利用JQuery ajax将参数ID传递给getData方法进行处理,getData方法处理完后返回JSON序列,将此序列绑定到城市下拉框里即可。

 

你可能感兴趣的:(Ajax)