ViewBag,ViewData,TempData,Session-如何以及何时使用它们? [英] ViewBag, ViewData, TempData, Session - how and when to use them?

查看:111
本文介绍了ViewBag,ViewData,TempData,Session-如何以及何时使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ViewData和ViewBag允许您访问从控制器传递来的视图中的任何数据.

ViewData and ViewBag allows you to access any data in view that was passed from controller.

这两者之间的主要区别在于您访问数据的方式. 在ViewBag中,您正在使用字符串作为键来访问数据-ViewBag [数字"] 在ViewData中,您正在使用属性-ViewData.numbers访问数据.

The main difference between those two is the way you are accessing the data. In ViewBag you are accessing data using string as keys - ViewBag["numbers"] In ViewData you are accessing data using properties - ViewData.numbers.

ViewData 示例

控制器

 var Numbers = new List<int> { 1, 2, 3 };

          ViewData["numbers"] = Numbers;

查看

<ul>
 @foreach (var number in (List<int>)ViewData["numbers"])
 {
     <li>@number</li> 
 }

 </ul>

ViewBag 示例

控制器

 var Numbers = new List<int> { 1, 2, 3 };

         ViewBag.numbers = Numbers;

查看

<ul>

@foreach (var number in ViewBag.numbers)

{
<li>@number</li> 
}

</ul>

会话是另一个非常有用的对象,它将保存所有信息.

Session is another very useful object that will hold any information.

例如,当用户登录到系统时,您要保留其授权级别.

For instance when user logged in to the system you want to hold his authorization level.

// GetUserAuthorizationLevel - some method that returns int value for user authorization level.

Session["AuthorizationLevel"] = GetUserAuthorizationLevel(userID);

只要用户会话处于活动状态,此信息将存储在会话中. 可以在Web.config文件中更改它:

This information will be stored in Session as long as user session is active. This can be changed in Web.config file:

<system.web>
    <sessionState mode="InProc" timeout="30"/>

然后在控制器内部执行操作:

So then in controller inside the action :

 public ActionResult LevelAccess()
     {
         if (Session["AuthorizationLevel"].Equals(1))
         {
             return View("Level1");
         }

        if (Session["AuthorizationLevel"].Equals(2))
        {
            return View("Level2");
        }

        return View("AccessDenied");
    }

TempData 与ViewData和ViewBag非常相似,但是它将仅包含一个请求的数据.

TempData is very similar to ViewData and ViewBag however it will contain data only for one request.

控制器

//您创建了一种添加新客户端的方法.

// You created a method to add new client.

TempData["ClientAdded"] = "Client has been added";

查看

@if (TempData["ClientAdded"] != null)
{ 
   <h3>@TempData["ClientAdded"] </h3>
}

当您要将某些信息从View传递到Controller时,

TempData很有用.例如,您想在请求查看时保留时间.

TempData is useful when you want to pass some information from View to Controller. For instance you want to hold time when view was requested.

查看

@{
TempData["DateOfViewWasAccessed"] = DateTime.Now;
}

控制器

if (TempData["DateOfViewWasAccessed"] != null)
   {
    DateTime time = DateTime.Parse(TempData["DateOfViewWasAccessed"].ToString()); 
   }

推荐答案

ViewBag,ViewData,TempData,会话-如何以及何时使用它们?

ViewBag, ViewData, TempData, Session - how and when to use them?

ViewBag

避免.尽可能使用视图模型.

ViewBag

Avoid it. Use a view model when you can.

原因是,当您使用动态属性时,不会出现编译错误.偶然或有意更改属性名称,然后忘了更新所有用法,真的很容易.

The reason is that when you use dynamic properties you will not get compilation errors. It's really easy to change a property name by accident or by purpose and then forget to update all usages.

如果使用ViewModel,则不会出现此问题.视图模型还将将MVC中的"M"(即业务实体)从控制器和视图转移到ViewModel的责任,因此您将获得职责明确的干净代码.

If you use a ViewModel you won't have that problem. A view model also moves the responsibility of adapting the "M" (i.e. business entities) in MVC from the controller and the view to the ViewModel, thus you get cleaner code with clear responsibilities.

操作

public ActionResult Index()
{
    ViewBag.SomeProperty = "Hello";
    return View();
}

查看(剃刀语法)

@ViewBag.SomeProperty

ViewData

请投票.尽可能使用视图模型.与使用ViewBag的原因相同.

ViewData

Avoit it. Use a view model when you can. Same reason as for ViewBag.

操作

public ActionResult Index()
{
    ViewData["SomeProperty"] = "Hello";
    return View();
}

查看(剃刀语法):

@ViewData["SomeProperty"]

温度数据

存储在TempData中的所有内容都将保留在tempdata中,直到您读取它为止,无论之间是否存在一个或多个HTTP请求.

Temp data

Everything that you store in TempData will stay in tempdata until you read it, no matter if there are one or several HTTP requests in between.

操作

public ActionResult Index()
{
    TempData["SomeName"] = "Hello";
    return RedirectToAction("Details");
}


public ActionResult Details()
{
    var someName = TempData["SomeName"];
}

这篇关于ViewBag,ViewData,TempData,Session-如何以及何时使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆