Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have seen many posts about when to use ViewBag/ViewData vs ViewModel but i have not been able to find an explanation of the lifecycle of the ViewBag.

For example, i have two Action methods in one Controller:

// POST: /MyModel/Edit/5
[HttpPost]
public ActionResult Edit(MyModel _mymodel){}

and

// GET: /MyModel/Edit/5
public ActionResult Edit(int id){}

If i put some values in the ViewBag in the GET action method, to set up some Form labels, then when they user clicks 'Submit' button and the Form is posted back to the server via HTTP POST, the ViewBag values are no longer within the POST action method.

Can someone please explain (or provide reference to good article) the lifecycle of the ViewBag/ViewData ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
817 views
Welcome To Ask or Share your Answers For Others

1 Answer

The data you put in the ViewBag/ViewData is only available during the life-cycle of the request within which you populated it. MVC does not have post backs. If you need something to persist over more than a single request, you should use Session.

Here is a decent article about the differences between ViewData, ViewBag, and TempData: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...