ASP.NET MVC传递Model到视图的多种方式总结(一)__通用方式的使用
有多种方式可以将数据传递到视图,如下所示:
ViewDataViewBagPartialViewTempDataViewModelTuple
场景:
在视图页面,下拉框选择课程触发事件,分别显示老师课程表、学生上课表,如图:

相关的Model:
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
} public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
} public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
一、使用ViewData传递多个Model
□ HomeController
public ActionResult Index()
{
ViewData["Courses"] = _repository.GetCourses();
ViewData["Students"] = _repository.GetStudents();
ViewData["Teachers"] = _repository.GetTeachers();
return View();
}
□ Home/Index.cshtml
@using MvcApplication1.Models
@using System.Web.Helpers;
@{
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewDataDemo</title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
//隐藏
$('#students').hide();
$('#teachers').hide(); //点击课程下拉框
$('#sel').change(function() {
selectedCourseName = $('#sel').val().trim();
if (selectedCourseName == "--选择课程--") {
$('#students').hide();
$('#teachers').hide();
} else {
getTeacherTable();
getStudentTable();
$('#students').show();
$('#teachers').show();
}
});
}); var selectedCourseName;
//创建老师课程表
function getTeacherTable() {
$('#teachersTable').empty();
$('#teachersTable').append("<table id='tblTeachers'><tr><th>编号</th><th>姓名</th></tr></table>");
//把所有老师转换成json格式
var teachers = @Html.Raw(Json.Encode(ViewData["Teachers"]));
for (var i = 0; i < teachers.length; i++) {
var courses = teachers[i].Courses;
for (var j = 0; j < courses.length; j++) {
if (courses[j].Name == selectedCourseName) {
$('#tblTeachers').append("<tr><td>"+courses[i].Id+"</td><td>"+courses[i].Name+"</td></tr>");
}
}
}
} //创建学生上课表
function getStudentTable() {
$('#studentsTable').empty();
$('#studentsTable').append("<table id='tblStudents'><tr><th>编号</th><th>姓名</th></tr></table>");
var students = @Html.Raw(Json.Encode(ViewData["Students"]));
for (var i = 0; i < students.length; i++) {
var courses = students[i].Courses;
for (var j = 0; j < courses.length; j++) {
if (courses[j].Name == selectedCourseName) {
$('#tblStudents').append("<tr><td>"+courses[j].Id+"</td><td>"+courses[j].Name+"</td></tr>");
}
}
}
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td><h3>选择课程</h3></td>
<td>
<select id="sel">
<option>--选择课程--</option>
@foreach (var course in ViewData["Courses"] as List<Course>)
{
<option>@course.Name</option>
}
</select>
</td>
</tr>
</table>
</div>
<div id="teachers">
<h4>老师课程表</h4>
<div id="teachersTable"></div>
</div>
<div id="students">
<h4>学生上课表</h4>
<div id="studentsTable"></div>
</div>
</body>
</html>
@Html.Raw(Json.Encode(ViewData["Students"]))是把Model转换成json字符串,需要用到System.Web.Helpers,把此类库引用到项目,并且必须设置"复制到本地属性"为true,否则报错。

二、使用ViewBag传递多个Model
□ HomeController
public ActionResult ViewBagDemo()
{
ViewBag.Courses = _repository.GetCourses();
ViewBag.Students = _repository.GetStudents();
ViewBag.Teachers = _repository.GetTeachers();
return View();
}
□ Home/ViewBagDemo.cshtml
下拉框遍历课程改成:
@foreach (var course in ViewBag.Courses)
getTeacherTable()方法中改成:
var teachers = @Html.Raw(Json.Encode(ViewBag.Teachers));
getStudentTable()方法中改成:
var students = @Html.Raw(Json.Encode(ViewBag.Students));
三、使用部分视图传递多个Model
□ HomeController
public ActionResult PartialViewDemo()
{
List<Course> courses = _repository.GetCourses();
return View(courses);
} public ActionResult StudentsToPVDemo(string courseName)
{
IEnumerable<Course> courses = _repository.GetCourses();
var selectedCourseId = (from c in courses
where c.Name == courseName
select c.Id).FirstOrDefault();
IEnumerable<Student> students = _repository.GetStudents();
var studentsInCourse = students.Where(s => s.Courses.Any(c => c.Id == selectedCourseId)).ToList();
return PartialView("StudentPV", studentsInCourse);
} public ActionResult TeachersToPVDemo(string courseName)
{
IEnumerable<Course> courses = _repository.GetCourses();
var selectedCourseId = (from c in courses
where c.Name == courseName
select c.Id).FirstOrDefault();
IEnumerable<Teacher> teachers = _repository.GetTeachers();
var teachersForCourse = teachers.Where(t => t.Courses.Any(c => c.Id == selectedCourseId)).ToList();
return PartialView("TeacherPV", teachersForCourse);
}
□ Home/PartialViewDemo.cshmtl
@model IEnumerable<MvcApplication1.Models.Course>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PatialViewDemo</title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
//隐藏
$('#students').hide();
$('#teachers').hide(); //点击课程下拉框
$('#sel').change(function() {
selectedCourseName = $('#sel').val().trim();
if (selectedCourseName == "--选择课程--") {
$('#students').hide();
$('#teachers').hide();
} else {
getTeacherTable();
getStudentTable();
$('#students').show();
$('#teachers').show();
}
});
}); var selectedCourseName;
//创建老师课程表
function getTeacherTable() {
$.ajax({
url: "@Url.Action("TeachersToPVDemo","Home")",
type: 'Get',
data: { courseName: selectedCourseName },
success: function(data) {
$('#teachersTable').empty().append(data);
},
error: function() {
alert("sth wrong");
}
});
} //创建学生上课表
function getStudentTable() {
$.ajax({
url: "@Url.Action("StudentsToPVDemo","Home")",
type: 'Get',
data: { courseName: selectedCourseName },
success: function (data) {
$('#studentsTable').empty().append(data);
},
error: function () {
alert("sth wrong");
}
});
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td><h3>选择课程</h3></td>
<td>
<select id="sel">
<option>--选择课程--</option>
@foreach (var course in Model)
{
<option>@course.Name</option
}
</select>
</td>
</tr>
</table>
</div>
<div id="teachers">
<h4>老师课程表</h4>
<div id="teachersTable"></div>
</div>
<div id="students">
<h4>学生上课表</h4>
<div id="studentsTable"></div>
</div>
</body>
</html>
□ TeacherPV.cshtml与StudentPV.cshtml
@model IEnumerable<MvcApplication1.Models.Teacher>
<table id="tblTeacherDetail">
<tr>
<th>编号</th>
<th>名称</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
</tr>
}
</table>
四、使用TempData传递多个Model
□ HomeController
public ActionResult TempDataDemo()
{
//第一次从数据库读取数据放到TempData中,以后的请求从TempData中获取数据
TempData["Courses"] = _repository.GetCourses();
//让TempData保存数据,直到下一次请求
TempData.Keep("Courses");
return View();
} public ActionResult TeachersTempData(string courseName)
{
var courses = TempData["Courses"] as IEnumerable<Course>;
//由于TempData["Courses"]还要被下一次请求,继续TempData保存数据
TempData.Keep("Courses");
var selectedCourseId = (from c in courses
where c.Name == courseName
select c.Id).FirstOrDefault();
IEnumerable<Teacher> teachers = _repository.GetTeachers();
var teachersForCourse = teachers.Where(t => t.Courses.Any(c => c.Id == selectedCourseId)).ToList();
return PartialView("TeacherPV", teachersForCourse);
} public ActionResult StudentsTempData(string courseName)
{
var courses = TempData["Courses"] as IEnumerable<Course>;
//由于TempData["Courses"]还要被下一次请求,继续TempData保存数据
TempData.Keep("Courses");
var selectedCourseId = (from c in courses
where c.Name == courseName
select c.Id).FirstOrDefault();
IEnumerable<Student> students = _repository.GetStudents();
var studentsForCourse = students.Where(s => s.Courses.Any(c => c.Id == selectedCourseId)).ToList();
return PartialView("StudentPV", studentsForCourse);
}
□ Home/TempDataDemo.cshtml
下拉框遍历课程:
@foreach (var course in Model)
ajax请求老师课程表:
@Url.Action("TeachersTempData","Home")
ajax请求学生上课表:
@Url.Action("StudentsTempData","Home")
五、使用ViewModel传递多个Model
□ View Model
public class SchoolVm
{
public List<Course> Courses { get; set; }
public List<Student> Students { get; set; }
public List<Teacher> Teachers { get; set; }
}
□ HomeController
public ActionResult ViewModelDemoVM()
{
SchoolVm vm = new SchoolVm();
vm.Courses = _repository.GetCourses();
vm.Teachers = _repository.GetTeachers();
vm.Students = _repository.GetStudents();
return View(vm);
}
□ Home/ViewModelDemoVM.cshtml
@model MvcApplication1.Models.SchoolVm
下拉框遍历课程:
@foreach (var course in Model.Courses)
ajax请求老师课程表和学生上课表:
@Html.Raw(Json.Encode(Model.Teachers))
@Html.Raw(Json.Encode(Model.Students))
六、使用Tuple传递多个Model
□ HomeController
public ActionResult TupleDemo()
{
var allModels = new Tuple<List<Course>, List<Teacher>, List<Student>>(_repository.GetCourses(),
_repository.GetTeachers(), _repository.GetStudents()) {};
return View(allModels);
}
□ Home/TupleDemo.cshtml
@model Tuple <List <MvcApplication1.Models.Course>, List <MvcApplication1.Models.Teacher>, List <MvcApplication1.Models.Student>>
下拉框遍历课程:
@foreach (var course in Model.Item1)
ajax请求老师课程表和学生上课表:
@Html.Raw(Json.Encode(Model.Item2))
@Html.Raw(Json.Encode(Model.Item3))
参考链接:https://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-M
ASP.NET MVC传递Model到视图的多种方式总结(一)__通用方式的使用的更多相关文章
- ASP.NET MVC传递Model到视图的多种方式总结
ASP.NET MVC传递Model到视图的多种方式总结 有多种方式可以将数据传递到视图,如下所示: ViewData ViewBag PartialView TempData ViewModel T ...
- ASP.NET MVC传递Model到视图的多种方式之通用方式的使用
ASP.NET MVC传递Model到视图的多种方式总结——通用方式的使用 有多种方式可以将数据传递到视图,如下所示: ViewData ViewBag PartialView TempData Vi ...
- ASP.NET MVC传递Model到视图的多种方式总结(二)__关于ViewBag、ViewData和TempData的实现机制与区别
在ASP.NET MVC中,视图数据可以通过ViewBag.ViewData.TempData来访问,其中ViewBag 是动态类型(Dynamic),ViewData 是一个字典型的(Diction ...
- ASP.NET MVC 3 Model【通过一简单实例一步一步的介绍】
今天主要讲Model的两个方面: 1. ASP.Net MVC 3 Model 简介 通过一简单的事例一步一步的介绍 2. ASP.Net MVC 3 Model 的一些验证 MVC 中 Model ...
- ASP.NET MVC 之Model的呈现
ASP.NET MVC 之Model的呈现(仅此一文系列三) 本文目的 我们来看一个小例子,在一个ASP.NET MVC项目中创建一个控制器Home,只有一个Index: public class H ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(2) - Binder Attribute
上篇文章中分析了Custom Binder的弊端: 由于Custom Binder是和具体的类型相关,比如指定类型A由我们的Custom Binder解析,那么导致系统运行中的所有Action的访问参 ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(1) - Custom Model Binder
在Asp.net MVC中, Model Binder是生命周期中的一个非常重要的部分.搞清楚Model Binder的流程,能够帮助理解Model Binder的背后发生了什么.同时该系列文章会列举 ...
- [转]ASP.NET MVC 2: Model Validation
本文转自:http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx?CommentPo ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(1)
Asp.net MVC的Model Binder工作流程以及扩展方法(1)2014-03-19 08:02 by JustRun, 523 阅读, 4 评论, 收藏, 编辑 在Asp.net MVC中 ...
随机推荐
- docker registry 私有仓库 安装配置、查询、删除
#++++++++++++++++++++++++++++++ #docker-registry 私有仓库 #搜索,下载register镜像 docker search registry docker ...
- SQL 必知必会 总结(一)
SQL必知必会 总结(一) 第 1 课 了解SQL 1.数据库(database): 保存有组织的数据容器(通常是一个文件或一组文件). 2.数据库管理系统(DBMS): 数据库软件,数据库是通过 D ...
- jmeter插件之自定义场景图(万能场景设计)
添加扩展插件 自定义线程组:jp@gc - Ultimate Thread Group 此线程组功能强大,可以实现多种场景设置,添加路径如图 参数含义解释 Start Threads Count:当前 ...
- 【qboi冲刺NOIP2017复赛试题4】 全套题目+题解+程序
作为一个好人(验题人),我给大家奉上下这套题的题解,并且预祝大家这套题能够AK: T1题面:Alice现在有n根木棍,他们长度为1,2,3....n,Bob想把某一些木棍去掉,使得Alice剩下的木棍 ...
- Linux驱动:LCD驱动框架分析
一直想花时间来整理一下Linux内核LCD驱动,却一直都忙着做其他事情去了,这些天特意抽出时间来整理之前落下的笔记,故事就这样开始了.LCD驱动也是字符设备驱动的一种,框架上相对于字符设备驱动稍微复杂 ...
- Linux 上安装 Couchbase服务
down: http://www.couchbase.com/downloads/ doc: http://docs.couchbase.com/archive-index/ forums: htt ...
- thread 带参数
在 .NET Framework 2.0 版中,要实现线程调用带参数的方法有两种办法. 第一种:使用ParameterizedThreadStart. 调用 System.Threading.Thre ...
- 不开vip会员照样看vip电影(亲测有效)
此为临时链接,仅用于文章预览,将在短期内失效关闭 不开vip会员照样看vip电影(亲测有效) 2018-03-08 mr_lee Python达人课堂 刚刚测试,真实有效,颇不接待要分享了... 土豪 ...
- Innosetup(pascal)标签控件label换行
Label1.AutoSize := false; //先关闭自适应 Label1.WordWrap := true; //开启换行
- ibatis(sqlmap)中 #与$的使用区别
在sqlmap文件中不使用“#VALUE#”来原样(参数对应什么类型,就当什么类型,比如拼凑的内容为string则自动加上了‘’)读取,而是$VALUE$方式来读取,即不加任何的东西,比如单引号啥的, ...