为什么viewbag值没有传回视图?

mke*_*ell 9 c# html5 asp.net-mvc-4

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

请指教..谢谢

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

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

我的编辑"ActionResult,只使用与索引相同的模型数据.

我的帖子"编辑"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);
}
Run Code Online (Sandbox Code Playgroud)

在我的索引视图中......

@if(@ViewBag.Message != null)
{
    <div>
        <button type="button">@ViewBag.Message</button>
    </div>
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 29

ViewBag仅适用于当前请求.在您的情况下,您正在重定向,因此您可能存储在ViewBag中的所有内容都将与当前请求一起消失.仅在呈现视图时使用ViewBag,而不是在您打算重定向时使用.

TempData改为使用:

TempData["Message"] = "Profile Updated Successfully";
return RedirectToAction("Index");
Run Code Online (Sandbox Code Playgroud)

然后在你看来:

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

在幕后,TempData将使用Session,但一旦你从中读取它就会自动逐出.所以它基本上用于短生命,一次重定向持久存储.

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