• 注册
当前位置:1313e > ajax >正文

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 { 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 { 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();}}
View Code

三、视图

添加视图Index.cshtml

下拉列表

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

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

 

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录