gpt4 book ai didi

asp.net-mvc-3 - ViewBag、ViewData 和 TempData

转载 作者:行者123 更新时间:2023-12-03 04:09:49 25 4
gpt4 key购买 nike

任何人都可以解释一下何时使用

  1. 临时数据
  2. 查看包
  3. 查看数据

我有一个要求,我需要在 Controller 一中设置一个值,该 Controller 将重定向到 Controller 二, Controller 二将渲染 View 。

我尝试使用 ViewBag,当我到达 Controller 二时,该值丢失了。

我可以知道何时使用以及优点或缺点吗?

谢谢

最佳答案

1)TempData

允许您存储重定向后仍保留的数据。在内部,它使用 Session 作为后备存储,在进行重定向后,数据将被自动驱逐。模式如下:

public ActionResult Foo()
{
// store something into the tempdata that will be available during a single redirect
TempData["foo"] = "bar";

// you should always redirect if you store something into TempData to
// a controller action that will consume this data
return RedirectToAction("bar");
}

public ActionResult Bar()
{
var foo = TempData["foo"];
...
}

2)ViewBag, ViewData

允许您将数据存储在将在相应 View 中使用的 Controller 操作中。这假设该操作返回一个 View 并且不重定向。仅在当前请求期间存在。

模式如下:

public ActionResult Foo()
{
ViewBag.Foo = "bar";
return View();
}

在 View 中:

@ViewBag.Foo

或使用 ViewData:

public ActionResult Foo()
{
ViewData["Foo"] = "bar";
return View();
}

在 View 中:

@ViewData["Foo"]

ViewBag 只是 ViewData 的动态包装器,仅存在于 ASP.NET MVC 3 中。

话虽如此,这两个构造都不应该被使用。您应该使用 View 模型和强类型 View 。所以正确的模式如下:

查看模型:

public class MyViewModel
{
public string Foo { get; set; }
}

行动:

public Action Foo()
{
var model = new MyViewModel { Foo = "bar" };
return View(model);
}

强类型 View :

@model MyViewModel
@Model.Foo
<小时/>

在简短的介绍之后,让我们回答您的问题:

My requirement is I want to set a value in a controller one, that controller will redirect to ControllerTwo and Controller2 will render the View.

public class OneController: Controller
{
public ActionResult Index()
{
TempData["foo"] = "bar";
return RedirectToAction("index", "two");
}
}

public class TwoController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = TempData["foo"] as string
};
return View(model);
}
}

和相应的 View (~/Views/Two/Index.cshtml):

@model MyViewModel
@Html.DisplayFor(x => x.Foo)
<小时/>

使用 TempData 也有缺点:如果用户在目标页面上按 F5,数据将会丢失。

就我个人而言,我也不使用 TempData。这是因为它在内部使用 session ,而我在应用程序中禁用 session 。我更喜欢一种更 RESTful 的方式来实现这一目标。即:在执行重定向的第一个 Controller 操作中,将对象存储在数据存储中,并在重定向时使用生成的唯一 ID。然后在目标操作上使用此 id 来取回最初存储的对象:

public class OneController: Controller
{
public ActionResult Index()
{
var id = Repository.SaveData("foo");
return RedirectToAction("index", "two", new { id = id });
}
}

public class TwoController: Controller
{
public ActionResult Index(string id)
{
var model = new MyViewModel
{
Foo = Repository.GetData(id)
};
return View(model);
}
}

View 保持不变。

关于asp.net-mvc-3 - ViewBag、ViewData 和 TempData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com