本例使用的是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

相关文章:

  • 2022-12-23
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2021-11-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-01-18
相关资源
相似解决方案