C# 为什么 viewbag 值不传递回视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19294975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:40:22  来源:igfitidea点击:

Why isn't viewbag value passing back to the view?

c#htmlasp.net-mvc-4

提问by mkell

straight forward question , can't seem to get my viewBag value to display in a view that the user is directed to after completing a form.

直截了当的问题,似乎无法让我的 viewBag 值显示在完成表单后用户被定向到的视图中。

Please advise..thanks

请指教。。谢谢

My Index ActionResult simple returns model data..

我的索引 ActionResult 简单返回模型数据..

public ActionResult Index()
{
    var source = _repository.GetByUserID(_applicationUser.ID);
    var model = new RefModel
    {
        test1 = source.test1,
    };
    return View(model);
}

My Get Edit" ActionResult , simply uses the same model data as Index.

My Get Edit” ActionResult ,只需使用与索引相同的模型数据。

My Post "Edit" ActionResult, assigns the new values if any to the model and redirects to the Index page, but Index page does not display ViewBag value ??

我的帖子“编辑”ActionResult,将新值(如果有)分配给模型并重定向到索引页面,但索引页面不显示 ViewBag 值?

[HttpPost]
public ActionResult Edit(RefModell model)
{
    if (ModelState.IsValid)
    {
        var source = _repository.GetByUserID(_applicationUser.ID);
        if (source == null) return View(model);

        source.test1 = model.test1;
        _uow.SaveChanges();

        @ViewBag.Message = "Profile Updated Successfully";
        return RedirectToAction("Index");      
    }
    return View(model);
}

And in my Index view...

在我的索引视图中...

@if(@ViewBag.Message != null)
{
    <div>
        <button type="button">@ViewBag.Message</button>
    </div>
}

采纳答案by Darin Dimitrov

ViewBag only lives for the current request. In your case you are redirecting, so everything you might have stored in the ViewBag will die along wit the current request. Use ViewBag, only if you render a view, not if you intend to redirect.

ViewBag 只对当前请求有效。在您的情况下,您正在重定向,因此您可能存储在 ViewBag 中的所有内容都将随着当前请求而消失。仅当您呈现视图时才使用 ViewBag,而不是您打算重定向时。

Use TempDatainstead:

使用TempData来代替:

TempData["Message"] = "Profile Updated Successfully";
return RedirectToAction("Index");

and then in your view:

然后在您看来:

@if (TempData["Message"] != null)
{
    <div>
        <button type="button">@TempData["Message"]</button>
    </div>
}

Behind the scenes, TempData will use Session but it will automatically evict the record once you read from it. So it's basically used for short-living, one-redirectpersistence storage.

在幕后,TempData 将使用 Session,但一旦您从中读取记录,它将自动驱逐记录。所以它基本上用于短期的单重定向的持久化存储。

Alternatively you could pass it as query string parameter if you don't want to rely on sessions (which is probably what I would do).

或者,如果您不想依赖会话(这可能是我会做的),您可以将其作为查询字符串参数传递。

回答by Natan

RedirectToAction causes an HTTP 302 response, which makes the client make another call to the server and request a new page.

RedirectToAction 导致 HTTP 302 响应,这使客户端再次调用服务器并请求新页面。

You should be returning a view instead of redirecting.

您应该返回视图而不是重定向。

回答by Kristof

The RedirectToAction(msdn) instructs your browser to make a new request.
So your server will be called again but it will be a new request with a blank viewbag and all
You could do a sort of internal redirect by just calling the index method, this way the viewbag will still have its data.

RedirectToAction( msdn) 指示您的浏览器发出新请求。
因此,您的服务器将再次被调用,但它将是一个带有空白视图包的新请求,
您只需调用 index 方法即可进行某种内部重定向,这样视图包仍将保留其数据。

Edit : you'll also have to modify your index method or your View(model) line will try to render the edit.
Full code below

编辑:您还必须修改索引方法,否则您的 View(model) 行将尝试呈现编辑。
完整代码如下

public ActionResult Index()
{
    var source = _repository.GetByUserID(_applicationUser.ID);
    var model = new RefModel
    {
        test1 = source.test1,
    };
    return View("Index",model);
}


[HttpPost]
public ActionResult Edit(RefModell model)
{
    if (ModelState.IsValid)
    {
        var source = _repository.GetByUserID(_applicationUser.ID);
        if (source == null) return View(model);

        source.test1 = model.test1;
        _uow.SaveChanges();

        @ViewBag.Message = "Profile Updated Successfully";
        return Index();      
    }
    return View(model);
}

回答by Ganganath Rathnasekara

You can try this way also

你也可以试试这个方法

Controller

控制器

public ActionResult Test()
    {
ViewBag.controllerValue= "testvalue";
 ..................
    }

View- define top of razor page @{string testvalue= (string)ViewBag.controllerValue;}

查看- 定义剃刀页面的顶部 @{string testvalue= (string)ViewBag.controllerValue;}

$(function () {
       var val= '@testvalue';
});