MVC控制器传递多个Model到视图,使用ViewData, ViewBag, 部分视图, TempData, ViewModel, Tuple
从控制器传递多个Model到视图,可以通过ViewData, ViewBag, PartialView, TempData, ViewModel,Tuple等,本篇逐一体验。本篇源码在github。
在视图页面,下拉框选择课程触发事件,分别显示老师课程表、学生上课表,如图:
相关的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; }
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
使用ViewData传递多个Model
□ HomeController
public ActionResult Index()
{
ViewData["Courses"] = _repository.GetCourses();
ViewData["Students"] = _repository.GetStudents();
ViewData["Teachers"] = _repository.GetTeachers();
return View();
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
@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();
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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);
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
使用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);
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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; }
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ HomeController
public ActionResult ViewModelDemoVM()
{
SchoolVm vm = new SchoolVm();
vm.Courses = _repository.GetCourses();
vm.Teachers = _repository.GetTeachers();
vm.Students = _repository.GetStudents();
return View(vm);
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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);
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 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))
参考资料:
※ Using Multiple Models in a View in ASP.NET MVC 4 / MVC 5
MVC控制器传递多个Model到视图,使用ViewData, ViewBag, 部分视图, TempData, ViewModel, Tuple的更多相关文章
- MVC控制器传递多个实体类集合到视图的方案总结
MVC控制器向视图传递数据包含多个实体类的解决方案有很多,这里主要针对视图模型.动态模型以及Tuple三种方法进行一些总结与记录. 基础集合类:TableA namespace ViewModelSt ...
- .net mvc控制器传递方法到视图
很多人都是在视图里面定义方法,然后再使用.我个人也是这么干的.但是为了验证是否可以将方法从控制器传递到视图,所以做了个测试.结果真的可以.原理是利用了委托(delegate),因为委托本身就是一种类型 ...
- MVC使用jQuery从视图向控制器传递Model,数据验证,MVC HTML辅助方法小结
//MVC HTML辅助类常用方法记录 (1)@Html.DisplayNameFor(model => model.Title)是显示列名, (2)@Html.DisplayFor(model ...
- MVC使用jQuery从视图向控制器传递Model的2种方法
http://blog.csdn.net/make1828/article/details/29846003 using System.ComponentModel.DataAnnotations; ...
- ASP.NET MVC 5 - 将数据从控制器传递给视图
在我们讨论数据库和数据模型之前,让我们先讨论一下如何将数据从控制器传递给视图.控制器类将响应请求来的URL.控制器类是给您写代码来处理传入请求的地方,并从数据库中检索数据,并最终决定什么类型的返回结果 ...
- Asp.Net Mvc 控制器与视图的数据传递
数据传递也就是控制器和视图之间的交互,比如在视图中提交的数据,在控制器怎么获取,或者控制器从业务层获得一些数据,怎么传递到视图中,让视图显示在客户端呢?带着这些疑问,我们接着看.. 下面 ...
- ASP.NET MVC 5 学习教程:控制器传递数据给视图
原文 ASP.NET MVC 5 学习教程:控制器传递数据给视图 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字 ...
- MVC 5 - 将数据从控制器传递给视图
MVC 5 - 将数据从控制器传递给视图 在我们讨论数据库和数据模型之前,让我们先讨论一下如何将数据从控制器传递给视图.控制器类将响应请求来的URL.控制器类是给您写代码来处理传入请求的地方,并从数据 ...
- 【ASP.NET MVC系列】浅谈ASP.NET MVC 视图与控制器传递数据
ASP.NET MVC系列文章 [01]浅谈Google Chrome浏览器(理论篇) [02]浅谈Google Chrome浏览器(操作篇)(上) [03]浅谈Google Chrome浏览器(操作 ...
随机推荐
- SQL存储过程相关信息查看
--1.查看所有存储过程与函数 exec sp_stored_procedures 或者 select * from dbo.sysobjects where OBJECT ...
- Linux学习笔记:ls和ll命令
list显示当前目录中的文件名字,不加参数时显示除隐藏文件外的所有文件及目录的名字. ll 等同于 ls -l-r 对目录反向排序(按字母)-t 以时间排序-u 以文件上次被访问的时间排序-x 按列输 ...
- 聚类:(K-means)算法
1.归类: 聚类(clustering) 属于非监督学习 (unsupervised learning) 无类别标记(class label) 2.举例: 3. K-means 算法: ...
- hdu 2069 1 5 10 25 50 这几种硬币 一共100个(母函数)
题意: 有50 25 10 5 1 的硬币 一共最多有100枚 输入n输出有多少种表示方法 Sample Input1126 Sample Output413 # include <iostre ...
- 一个带bash,带glibc,中国时区,非root用户可运行crond命令的基于alpine镜像的Dockerfile
这个镜像现在说起来简单, 带bash(增加执行脚本的兼容性,带GLIBC,中国时区,非root用户可运行crond命令-安全) 但让我开始陷入时,真的让我有段时间有点爆了. 比如,将filebeat文 ...
- UVA 10559 Blocks(区间DP&&递推)
题目大意:给你玩一个一维版的消灭星星,得分是当前消去的区间的长度的平方,求最大得分. 现在分析一下题目 因为得分是长度的平方,不能直接累加,所以在计算得分时需要考虑前一个状态所消去的长度,仅用dp[l ...
- Bechmarksql
使用方法 1.配置JDK环境 JDK最好是1.5以上的版本 JAVA_HOME=/usr/java/jdk1.6.0_22 PATH=$PATH:$JAVA_HOME/bin 2.准备工作 把要测试的 ...
- 9-1 A Spy in the Metro uva1025 城市里的间谍 (DP)
非常有价值的dp题目 也是我做的第一题dp 真的效率好高 题意:某城市的地铁是线性的 有n个车站 从左到右编号为1-n 有m1辆列车从第一站开始往右开 还有m2辆列车从第n站开始往左开 在 ...
- ubuntu16.04 安装symfony3.3.11 碰到的问题:extension dom is required | oops an error occurred 500
问题1:Uncaught exception 'RuntimeException' with message 'Extension DOM is required' 解决:sudo apt-get i ...
- Oracle数据库脚本中的set define off
2018年8月6日15:11:34 Oracle数据库脚本中的set define off 前言 最近在公司写需求,接触到脚本,第一句set define off;就不知道什么意思了,查询后记录之. ...