MVC,控制器向视图传递数据的方式:
- ViewData[“key”] = value, value可以为任意类型的数据
control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UI.Models;
namespace UI.Controllers
{
public class StudentController : Controller
{
//
// GET: /Student/
public ActionResult ABC()
{
string msg = "这是控制器传递给视图的数据.....";
ViewData[ "msg" ] = msg;
Student s1 = new Student { Id = 100 , Name = "东方不败" };
ViewData[ "student" ] = s1;
List<Student> lst = new List<Student>( ){
new Student{Id=101,Name="张无忌"},
new Student{Id=102,Name="张翠山"},
new Student{Id=103,Name="张三丰"},
new Student{Id=104,Name="张松溪"}
};
ViewData[ "list" ] = lst;
return View();
}
}
}
view
@using UI.Models;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ABC</title>
</head>
<body>
<div>
@{
Student s1 = ViewData[ "student" ] as Student;
}
<h1>学生管理平台</h1>
<h2>@ViewData["msg"].ToString()</h2>
<h3>学生姓名:@s1.Name</h3>
<div>
<ul>
@{
List<Student> lst = ViewData["list"] as List<Student>;
foreach ( var std in lst)
{
<li>@std.Name</li>
}
}
</ul>
</div>
</div>
</body>
</html>
- 具有动态类型的对象
ViewBag.key = value,无须进行类型转换
control
public ActionResult ViewBagDemo( )
{
string sql = "select * from book";
DataTable dt = DBHelper.Query( sql , null , false );
List<Book> books = new List<Book>( );
foreach ( DataRow row in dt.Rows )
{
Book bk = new Book
{
BID = Convert.ToInt32( row[ "bid" ] ) ,
BName = row[ "bname" ].ToString( ) ,
BCount = Convert.ToInt32( row[ "bcount" ] )
};
books.Add( bk );
}
ViewBag.books = books;
return View( );
}
view`
@using UI.Models;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewBagDemo</title>
<style type="text/css">
.tab
{
width:50%;
border:solid 1px blue;
border-collapse:collapse;
}
.tab td
{
text-align:center;
border:solid 1px blue;
}
</style>
</head>
<body>
<h1>ViewBag案例</h1>
<div>
<table class="tab">
<tr>
<td>书号</td>
<td>标题</td>
<td>库存</td>
</tr>
@{
foreach ( var bk in ViewBag.books )
{
<tr>
<td>@bk.BID</td>
<td>@bk.BName</td>
<td>@bk.BCount</td>
</tr>
}
}
</table>
</div>
</body>
</html>
- TempData[“key”] = value,它可以在Action之间共享数据
control
public ActionResult TempDate( )
{
TempData[ "book" ] = new Book
{
BID = 100 ,
BName = "雪山飞狐" ,
BCount = 10
};
//跳转到指定的Action中
return RedirectToAction( "AccepTempData" );
}
public ActionResult AccepTempData( )
{
Book bk = TempData[ "book" ] as Book;
ViewBag.book = bk;
return View( );
}
}
view
@using UI.Models;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div><a href="/Student/ABC">ViewData传递数据</a></div>
<div><a href="/Book/BookList">图书列表(ViewData)</a></div>
<div><a href="/Book/ViewBagDemo">图书列表(ViewBag)</a></div>
<div><a href="/Book/TempDate">TempData案例</a></div>
<div>
@{
if ( ViewData["books"] !=null )
{
List<Book> books = ViewData[ "books" ] as List<Book>;
foreach ( var bk in books )
{
<div>@bk.BName</div>
}
}
}
</div>
</body>
</html>