
MVC学习系列6--使用Ajax加载分部视图和Json格式的数据
Book Publisher BookMap PublisherMap MyDbContext
发布日期:2021-05-09 01:05:09
浏览次数:17
分类:博客文章
本文共 9184 字,大约阅读时间需要 30 分钟。
Ajax的应用在平时的工作中,很是常见,这篇文章,完全是为了,巩固复习。
我们先看看不使用json格式返回分部视图:
先说需求吧:
我有两个实体,一个是出版商【Publisher】,一个是书【Book】(很显然这是一对多的关系,一个出版商可以出版很多书籍,一本书只有一个出版商。),这里,我要实现的是,在出版商页面,使用DropDownList加载出来有哪些出版商,然后选择出版商的时候,异步加载分部视图,加载这个出版商出版的书籍的数据。
打算使用EF来做,也当是一个复习吧:
1.首先新建一个空白的MVC web项目:,在Model文件夹下面新建两个实体:
BOOK实体:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace AjaxDataInMVC.Models{ public class Book { public int BookID { get; set; } public string Title { get; set; } public string Auther { get; set; } public string Price { get; set; } public string Year { get; set; } public int PublisherID { get; set; } public virtual Publisher Publisher { get; set; } }}
Punlisher实体:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace AjaxDataInMVC.Models{ public class Publisher { ////// 出版编号 /// public int PublisherID { get; set; } ////// 出版商名称 /// public string PublisherName { get; set; } ////// 出版日期 /// public string PublisherYear { get; set; } public virtual ICollectionBooks { get; set; } }}
2.接着,添加EF引用,然后在根目录下,新建一个Map文件夹,在里面新建两个实体:
using AjaxDataInMVC.Models;using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Web;namespace AjaxDataInMVC.Map{ public class BookMap:EntityTypeConfiguration{ public BookMap() { //设置主键 this.HasKey(x => x.BookID); this.Property(x => x.BookID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(x => x.Price).IsRequired(); this.Property(x => x.Auther).IsRequired().HasMaxLength(50); this.Property(x => x.Title); this.Property(x => x.Year); this.HasRequired(x => x.Publisher).WithMany(x => x.Books).HasForeignKey(x => x.PublisherID).WillCascadeOnDelete(true); this.ToTable("Books"); } }}
using AjaxDataInMVC.Models;using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Web;namespace AjaxDataInMVC.Map{ public class PublisherMap:EntityTypeConfiguration{ public PublisherMap() { //主键 this.HasKey(x => x.PublisherID); this.Property(x => x.PublisherID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(x => x.PublisherName).HasMaxLength(50).IsRequired(); this.Property(x => x.PublisherYear).IsRequired(); this.ToTable("Publishers"); } }}
3.现在就是新建数据上下文类了,在Map文件夹下:
using System;using System.Collections.Generic;using System.Data.Entity;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Reflection;using System.Web;namespace AjaxDataInMVC.Map{ public class MyDbContext:DbContext { public MyDbContext() : base("name=DbConnectionString") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } // base.OnModelCreating(modelBuilder); } }}
别忘了,配置文件中加上:
5.这里特别提到,创建下拉框,我们可以新建一个ViewModel性质的实体
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Web;using System.Web.Mvc;namespace AjaxDataInMVC.ViewModel{ public class PublisherViewModel { public PublisherViewModel() { PublisherList = new List(); } [Display(Name="PublishName")] public int PublisherID { get; set; } public IEnumerable PublisherList { get; set; } }}
4.创建对应的控制器:
using AjaxDataInMVC.Map;using AjaxDataInMVC.Models;using AjaxDataInMVC.ViewModel;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace AjaxDataInMVC.Controllers{ public class PublisherController : Controller { private MyDbContext context; public PublisherController() { context = new MyDbContext(); //检测到循环引用可以加上这句 context.Configuration.ProxyCreationEnabled = false; } // GET: Publisher public ActionResult Index() { ListlstPublisher = context.Set ().ToList(); PublisherViewModel model = new PublisherViewModel(); model.PublisherList = lstPublisher.Select(x => new SelectListItem() { Text = x.PublisherName, Value = x.PublisherID.ToString() }); return View(model); } }}
using AjaxDataInMVC.Map;using AjaxDataInMVC.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace AjaxDataInMVC.Controllers{ public class BookController : Controller { private MyDbContext context; public BookController() { context = new MyDbContext(); context.Configuration.ProxyCreationEnabled = false; } // GET: Book public ActionResult Index() { return View(); } //直接返回布局页的方式:HTML public PartialViewResult GetBookDetailsByID(int id) { ListlstBook = context.Set ().Where(x => x.PublisherID.Equals(id)).ToList(); return PartialView(lstBook); } //Json方式 //public JsonResult GetBookDetailsByID(int id) //{ // List lstBook = context.Set ().Where(x => x.PublisherID.Equals(id)).ToList(); // return Json(lstBook,JsonRequestBehavior.AllowGet); //} }}
Publisher控制器的Index视图:
@model AjaxDataInMVC.ViewModel.PublisherViewModel@{ Layout = null;}Index @*思路是:在当前页面,点击下拉框,加载分部视图*@@Html.LabelFor(s=>s.PublisherID) @Html.DropDownListFor(s=>s.PublisherID,Model.PublisherList)
Book控制器的分部视图GetBookDetailsByID:
@model IEnumerable
@foreach (var item in Model) { BookID Title Auther Price Year } @item.BookID @item.Title @item.Auther @item.Price @item.Year
在数据库中写上测试数据,然后先运行一下:
选择:新华大学出版社,的时候,随即加载出了对应的数据。
选择:长江日报出版社的时候,加载:
现在看看:使用Json方式加载吧:
修改一下Book控制器,和其相关的Publisher控制器的Index视图就可以:
using AjaxDataInMVC.Map;using AjaxDataInMVC.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace AjaxDataInMVC.Controllers{ public class BookController : Controller { private MyDbContext context; public BookController() { context = new MyDbContext(); context.Configuration.ProxyCreationEnabled = false; } // GET: Book public ActionResult Index() { return View(); } ////直接返回布局页的方式:HTML //public PartialViewResult GetBookDetailsByID(int id) //{ // ListlstBook = context.Set ().Where(x => x.PublisherID.Equals(id)).ToList(); // return PartialView(lstBook); //} //Json方式 public JsonResult GetBookDetailsByID(int id) { List lstBook = context.Set ().Where(x => x.PublisherID.Equals(id)).ToList(); return Json(lstBook,JsonRequestBehavior.AllowGet); } }}
@model AjaxDataInMVC.ViewModel.PublisherViewModel@{ Layout = null;}Index @*思路是:在当前页面,点击下拉框,加载分部视图*@@Html.LabelFor(s=>s.PublisherID) @Html.DropDownListFor(s=>s.PublisherID,Model.PublisherList)
接着运行:
总结:这篇文章,完全为了复习巩固,另外在序列化Book实体,json 数据的时候,你可能会遇到这个错误:检测到循环依赖,因为我没有给Book实体新建一个ViewModel,这里可以这样解决:
context.Configuration.ProxyCreationEnabled = false; 禁用代理。 另外,使用Json格式返回数据,很快,比直接用HTML文本加载视图快很多。
Content Type | Header | Body | Total (Byte) |
text/html | 434 | 375 | 809 |
application/ json | 398 | 197 | 595 |
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年05月09日 13时00分17秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【阅读论文】博-自动化眼底图像分析技术可筛查糖尿病患者的视网膜疾病--第二章
2019-03-16
51单片机的复位电路
2019-03-16
OpenCV-Python图像梯度 Scharr算子
2019-03-16
java 原型模式(大话设计模式)
2019-03-16
java 中介者模式(大话设计模式)
2019-03-16
微机原理 6-计算机中常用的数制
2019-03-16
2.5 实际电源的两种模型及其等效变换
2019-03-16
MCS51 程序存储器(ROM)
2019-03-16
web访问ejb测试 详解
2019-03-16
window系统下安装使用curl命令工具
2019-03-16
假如计算机是中国人发明的,那代码应该这么写
2019-03-16
神器 Codelf !
2019-03-16
趣图:会算法和不会算法的区别
2019-03-16
一行代码就能解决的智力算法题
2019-03-16
区块链会2020再次爆发,先学点DAPP压压惊,跟我一起学《区块链DApp入门实战》
2019-03-16
问题解决28:微信网页授权出现redicet_uri 参数错误
2019-03-16
App的启动过程(2)framework侧-恢复最上层的Activity
2019-03-16
LeakCanary 中文使用说明
2019-03-16
反转链表,(5)
2019-03-16