gpt4 book ai didi

asp.net-mvc-3 - 使用 ViewData 将字符串从 Controller 传递到 ASP.NET MVC3 中的 View

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

我试图通过一个随机 string来自我的 ControllerView .

这是我的 Controller代码:

 [HttpPost]
public ActionResult DisplayForm(UserView user)
{
//some data processing over here
ViewData["choice"] = "Apple";

return RedirectToAction("Next", "Account");
}

现在我想将该数据值“Apple”传递给我的 View Next.cshtml其创建方式如下:
//View: Next.cshtml

@{
ViewBag.Title = "Thanks for registering";
Layout = "~/Content/orangeflower/_layout.cshtml";
}
<p>Your favorite fruit is:</p>@ViewData["choice"]

但是当项目运行时,我无法在浏览器中看到我的数据。

这是快照:

1) 在调试时, Controller 显示值:

enter image description here

2)浏览器 View 不显示值“Apple”

enter image description here

3) 进一步调试我的 Next.cshtml看法:
enter image description here

为什么值没有正确传递给 View 。我的 Controller NextDisplayForm在同一个 Controller 内 AccountController.cs ,仍然没有显示值(value)。

有人可以帮我解决这个问题吗?

最佳答案

您不是在渲染 View ,而是在重定向。如果您想向 View 传递一些信息,您需要在将其添加到 ViewData 后返回此 View 。 :

[HttpPost]
public ActionResult DisplayForm(UserView user)
{
//some data processing over here
ViewData["choice"] = "Apple";

return View();
}

如果您想传递重定向后仍然存在的消息,您可以使用 TempData而不是 ViewData .
[HttpPost]
public ActionResult DisplayForm(UserView user)
{
//some data processing over here
TempData["choice"] = "Apple";

return RedirectToAction("Next", "Account");
}

然后在 Next 操作中,您可以从 TempData 获取数据并将其存储在 ViewData 中,以便 View 可以读取它。

关于asp.net-mvc-3 - 使用 ViewData 将字符串从 Controller 传递到 ASP.NET MVC3 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8803597/

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