一,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>

三,使用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)); @Html.Raw(Json.Encode(ViewData["Students"]))是把Model转换成json字符串,需要用到System.Web.Helpers,把此类库引用到项目,并且必须设置"复制到本地属性"为true,否则报错。

四,使用部分视图传递多个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))

  

MVC几种传值方式的更多相关文章

  1. MVC 向页面传值方式总结(2)

    MVC 向页面传值方式总结 总结发现ASP.NET MVC中Controller向View传值的方式共有6种,分别是: ViewBag ViewData TempData 向普通View页面传一个Mo ...

  2. MVC 向页面传值方式总结(1)

    ViewData传值. HomeController.cs Co de: public ActionResult Index() {       ViewData["Title"  ...

  3. MVC中页面传值方式总结

    MVC中的页面传值,通常指Controller和view之间的数据传递,经常用到的有几种方式,总结如下: 一.Controller----------->View(控制器传到视图) 1.View ...

  4. iOS 页面间几种传值方式(属性,代理,block,单例,通知)

    第二个视图控制器如何获取第一个视图控制器的部分信息 例如 :第二个界面中的lable显示第一个界面textField中的文本 这就需要用到属性传值.block传值 那么第一个视图控制器如何获的第二个视 ...

  5. django之创建第7-6-第三种传值方式

    1.创建bar.html文件 <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  6. django之创建第7-5-第二种传值方式(time/1232/xiaodneg)

    1.修改views文件 def foo(request,myID,myName): t = loader.get_template("foo.html") user = {&quo ...

  7. Vue 常用三种传值方式

    Vue常用的三种传值方式: 父传子 子传父 非父子传值 引用官网一句话:父子组件的关系可以总结为 prop 向下传递,事件向上传递.父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消 ...

  8. Vue中常用的几种传值方式

    Vue中常用的几种传值方式 1. 父传子 父传子的实现方式就是通过props属性,子组件通过props属性接收从父组件传过来的值,而父组件传值的时候使用 v-bind 将子组件中预留的变量名绑定为da ...

  9. 简述UIViewControl之间的七种传值方式~~~

    将自己学习到的UIViewControl之间传值的几种方式在这里做一下总结,希望童鞋们多多支持哈--- 一.正向传值方式 这种方式传值应该是最简单的方式,我们先来建立两个视图控制器暂且称为OneVie ...

随机推荐

  1. Chapter 2 User Authentication, Authorization, and Security(3):保server避免暴力袭击

    原版的:http://blog.csdn.net/dba_huangzj/article/details/38756693,专题文件夹:http://blog.csdn.net/dba_huangzj ...

  2. 阿里云server安全设定

    1.打开所有的服务云盾 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamVkaWFlbF9sdQ==/font/5a6L5L2T/fontsize/400 ...

  3. jquery扩展

    jQuery插件的开发包括两种: 一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法.jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级 ...

  4. ASP.NET 5 (vNext)

    ASP.NET 5 (vNext) 理解和入门   概述 ASP.NET 5 (又称为vNext) 是自ASP.NET产生15年以来一次革命性的更新, 我们可以从以下几点来理解其概貌和意义: ASP. ...

  5. AJAX及其跨域的主要解决方法

    AJAX = Asynchronous JavaScript andXML(异步的 JavaScript 和 XML).通过在后台与服务器进行少量数据交换,使网页实现异步更新.要明白异步交互可以通过同 ...

  6. [Unity3D]Unity3D游戏开发之Unity与Android交互调用研究

    各位朋友,大家好,我是秦元培,欢迎大家关注我的博客,我的博客地址是blog.csdn.net/qinyuanpei.在前一篇文章中,我们研究了Android平台上Unity3D的手势操作并在之前的基础 ...

  7. jquery_mobile.js+html5+css3打造手机平板等各种效果

    http://www.w3school.com.cn/jquerymobile/jquerymobile_events_orientation.asp

  8. pyqt学习总结

    一.学习来由: 近期一段时间,应朋友的须要,完毕一款抓取软件.一般而言,python是我比較熟悉的语言,又有丰富的抓取和解析模块,所以果断选择之. 而这远远不是重点,后台程序在工作做常常写,所以比較熟 ...

  9. Windows socket之最简单的socket程序

    原文:Windows socket之最简单的socket程序 最简单的服务器的socket程序流程如下(面向连接的TCP连接 ): 1. WSAStartup(); 初始化网络库的使用. 2. soc ...

  10. 浅谈JavaScript性能

    最近在JavaScript性能方面有所感悟,把我的经验分给大家: 说到JavaScript,就不得不说它的代码的运行速度—— 在我初学JavaScript的时候,只是觉得它是一个很强大的脚本.渐渐的, ...