为什么视图包值没有传递回视图

本文关键字:视图 包值没 为什么 | 更新日期: 2023-09-27 18:34:48

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

请指教..谢谢

我的索引操作结果简单返回模型数据。

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

我的获取编辑"操作结果,只是使用与索引相同的模型数据。

我的帖子"编辑"操作结果,将新值(如果有(分配给模型并重定向到索引页面,但索引页面不显示 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)
{
    <div>
        <button type="button">@ViewBag.Message</button>
    </div>
}

为什么视图包值没有传递回视图

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

请改用TempData

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

然后在您看来:

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

在后台,TempData 将使用会话,但一旦您从中读取记录,它就会自动逐出记录。因此,它基本上用于短期的单重定向持久性存储。

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

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

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

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

编辑

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

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