加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 使用ViewData将字符串从Controller传递到ASP.N

发布时间:2020-12-16 04:18:32 所属栏目:asp.Net 来源:网络整理
导读:我试图从我的控制器传递一个随机字符串到视图. 这是我的控制器代码: [HttpPost] public ActionResult DisplayForm(UserView user) { //some data processing over here ViewData["choice"] = "Apple"; return RedirectToAction("Next","Account"); } 现在我
我试图从我的控制器传递一个随机字符串到视图.

这是我的控制器代码:

[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中,以便视图可以读取它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读