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

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

请指教..谢谢

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

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

我的获取编辑“ActionResult,只使用与索引相同的模型数据。

我的post“编辑”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); } 

在我的索引视图中……

 @if(@ViewBag.Message != null) { 
}

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

改为使用TempData

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

然后在你看来:

 @if (TempData["Message"] != null) { 
}

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

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

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

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

RedirectToAction( msdn )指示您的浏览器发出新请求。
因此,您的服务器将再次被调用,但它将是一个带有空白视图包的所有新请求
您可以通过调用索引方法来执行某种内部重定向,这样viewbag仍将拥有其数据。

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

 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); } 

你也可以尝试这种方式

调节器

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

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

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