前段时间,在项目中,运用到ASP.NET MVC 2.0技术,经常会遇到要在Controller与View之间数据传递的问题,现在在总结一下。

一、Controller向View传递数据

Controller向View传递数据有3种形式:

1、通过ViewData传递

在Controller里面定义ViewData,并且赋值,比如 ViewData["contact"] = contact;

然后在View里面读取Controller中定义的ViewData数据

比如联系人: <input type="text" value='<%=ViewData["contact"] %>' name="contact"/>

 

2、通过TempData传递

与ViewData的使用和传递方式相类似,现在在Controller里面定义TempData,并且赋值,比如 TempData["message"] = “你好!”;

然后在View里面读取Controller中定义的TempData数据

比如联系人: <input type="text" value='<%=TempData["message"] %>' name="message"/>

 

3、通过强类型的ViewModel传递

我们先创建一个ListViewData,它是泛型类型的,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
   5:  
namespace QQYDT.Help.PageHelp
   7: {
class ListViewData<T>
   9:     {
public ListViewData()
  11:         {
new List<T>();
  13:         }
  14:  
int PageSize
  16:         {
  17:             get;
  18:             set;
  19:         }
  20:  
int _currentPage;
int CurrentPage
  23:         {
  24:             get
  25:             {
return _currentPage;
  27:             }
  28:             set
  29:             {
value;
  31:             }
  32:         }
  33:  
public List<T> PageData
  35:         {
  36:             get;
  37:             set;
  38:         }
int PageDataCount
  40:         {
  41:             get;
  42:             set;
  43:         }
  44:  
int PageCount
  46:         {
  47:             get
  48:             {
int count = PageCalculator.TotalPage(PageDataCount, PageSize);
  50:  
return count;
  52:             }
  53:  
  54:         }
  55:  
int ShowType
  57:         {
  58:             get;
  59:             set;
  60:         }
  61:     }
  62: }

相关文章: