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

前端 未结 4 1222
傲寒
傲寒 2020-12-11 02:08

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.

Please advise..thanks

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 02:53

    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.

    Use TempData instead:

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

    and then in your view:

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

    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-redirect persistence storage.

    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).

提交回复
热议问题