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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 使用ViewData将字符串从Controller传递到ASP.NET MVC3中的View前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从我的控制器传递一个随机字符串到视图.

这是我的控制器代码

  1. [HttpPost]
  2. public ActionResult DisplayForm(UserView user)
  3. {
  4. //some data processing over here
  5. ViewData["choice"] = "Apple";
  6.  
  7. return RedirectToAction("Next","Account");
  8. }@H_403_5@
  9. 现在我想将该数据值“Apple”传递给我的视图Next.cshtml,其创建方式如下:

  10. //View: Next.cshtml
  11.   @{
  12.     ViewBag.Title = "Thanks for registering";
  13.     Layout = "~/Content/orangeflower/_layout.cshtml";
  14.    }
  15.     <p>Your favorite fruit is:</p>@ViewData["choice"]@H_403_5@ 
  16.  

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

  17.  

    这是快照:

  18.  

    1)在调试时,控制器显示值:

  19.  

    2)浏览器视图未显示值“Apple

  20.  

    3)进一步调试到我的Next.cshtml视图:

  21.  

    为什么值没有正确传递给View.我的NextDisplayForm控制器都在同一个Controller AccountController.cs中,仍然没有显示值.

  22.  

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

解决方法

您没有渲染视图,而是重定向.如果您想要在视图中传递一些信息,则需要在将视图添加到ViewData后返回此视图:
  1. [HttpPost]
  2. public ActionResult DisplayForm(UserView user)
  3. {
  4. //some data processing over here
  5. ViewData["choice"] = "Apple";
  6.  
  7. return View();
  8. }@H_403_5@
  9. 如果要传递在重定向后仍然存在的消息,则可以使用TempData而不是ViewData.

  10. [HttpPost]
  11. public ActionResult DisplayForm(UserView user)
  12. {
  13.     //some  data processing over here
  14.     TempData["choice"] = "Apple";
  15.     return RedirectToAction("Next","Account");
  16. }@H_403_5@ 
  17.  

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

猜你在找的asp.Net相关文章