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

我试图从我的控制器传递一个随机字符串到视图.

这是我的控制器代码

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

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

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

//View: Next.cshtml

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

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

这是快照:

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

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

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

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

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

解决方法

您没有渲染视图,而是重定向.如果您想要在视图中传递一些信息,则需要在将视图添加到ViewData后返回此视图:
[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中,以便视图可以读取它.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....