您的位置:首页 > 其它

MVC进阶学习--View和Controller之间的数据传递(一)

2009-10-29 20:52 501 查看
1.使用ViewData

  ViewData 的是ControllerBase 的一个属性,是一个数据字典类型的,其实现代码如(这段代码来自asp.net MVC开源项目中源码)下:

265
266 // If the container is a ViewDataDictionary then treat its Model property
267 // as the container instead of the ViewDataDictionary itself.
268 ViewDataDictionary vdd = container as ViewDataDictionary;
269 if (vdd != null) {
270 container = vdd.Model;
271 }
272
273 // Second, we try to use PropertyDescriptors and treat the expression as a property name
274 PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container).Find(propertyName, true);
275 if (descriptor == null) {
276 return null;
277 }
278
279 return descriptor.GetValue(container);
280 }
281
282 private struct ExpressionPair {
283 public readonly string Left;
284 public readonly string Right;
285
286 public ExpressionPair(string left, string right) {
287 Left = left;
288 Right = right;
289 }
290 }
291 }
292
293 #region IEnumerable Members
294 [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
295 IEnumerator IEnumerable.GetEnumerator() {
296 return ((IEnumerable)_innerDictionary).GetEnumerator();
297 }
298 #endregion
299
300 }
  ViewData的用法如下:ViewData["user"] = LoginUser; 页面的代码<%=(ViewData["user"] as Users).UserName%>

  ViewData的作用域从控制器设置值到页面值显示。

2.使用TempData

  TempData同样属于ControllerBase 的属性 用法和ViewData 基本相同,但是他们的实质是不同的,ViewData 是数据字典类型而TempData是Session存储的值,TempData数据只能在控制器中传递一次,每个元素也只能被访问一次,然后Session中的值就会被自动删除,它的生命周期要比ViewData的要长.

 

3.使用Model

  使用Model 顾名思义就是将一个实体对象绑定在页面上,上面两种都是放在作用域中。这里只讲用法。

  public ActionResult Student()

  {

    DbContext context=new DbContext();

    Student stu=context.Single(s=>s.ID==1);

    return View(stu);

  }

  页面代码的使用:<%=(Model as MVCTest.Models.Student).Name %> Model 是ViewPage d的一个属性值,用于     接收控制器中返回的值

  Model 传输数据还可以这样用:

  <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCTest.Models.Student>" %>

  <%=Model.Name %>

  使用泛型的ViewPage,将Model中的值指定特定类型不用强制性转换

4.传递多个对象类型

  其实传递多个对象类型,最简单的办法就是将这些对象封装成另外一个类的属性,然后将这个对象传递到页面。不在做介绍

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: