Any reason why my ViewBag is not working?

前端 未结 3 1285
梦如初夏
梦如初夏 2021-01-05 23:05

I have following ActionResult in a controller and you can see that I set a message in the ViewBag if it\'s successful. Then on the

相关标签:
3条回答
  • 2021-01-05 23:19

    The viewbag/viewdata scope is available for controller to view only. if you use tempdata, it will available one request , you can extend more than one request

    0 讨论(0)
  • 2021-01-05 23:24

    The ViewBag property enables you to dynamically share values from the controller to the view. (MSDN)

    It’s life lies only during the current request, and if redirection occurs then it’s value becomes null. And since you using RedirectToAction, which redirects to some different controller, value of ViewBag is lost.

    Consider using TempData instead.

    TempData["ResultMessage"] = "Role created successfully.";
    

    (See this for usage)

    0 讨论(0)
  • 2021-01-05 23:31

    ViewBag helps to maintain data when you move from controller to view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

    Since you are using RedirectToAction, the ViewBag becomes null when it reaches the view.

    you can use TempData for this:

    TempData["ResultMessage"] = "Role created successfully.";
    

    It uses Session as storage, but it will not be around after the second response. TempData helps to maintain data when you move from one controller to other controller or from one action to other action. In other words, when you redirect, Tempdata helps to maintain data between those redirects. It internally uses session variables. TempData use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view.

    For more understanding on this refer this link

    0 讨论(0)
提交回复
热议问题