I have a logical question that needs to be answered!!
Here is a scenario..
-In controller
ViewBag.Name = "aaaa";
-In View
@ViewBag.Name
"In my controller, i have set value for ViewBag and retrieved value from ViewBag in VIew. Now in View, i have a button, which is posting some data to a HttpPost method. In HttpPost method, i have changed the values for ViewBag. So after the execution of that method, the values in the viewbag will change or not for current view??"
-In HttpPost Method
ViewBag.Name="bbbb";
Best Answer
The ViewBag data you set on an action method will be available only to the immediate view which you are using. It will not be availabe when you post it back to your server unless you keep that in a hidden variable inside the form. That means, after you change your ViewBag data in your HttpPost action method, you can see that in the view you are returning
Assuming your view is printing the ViewBag data
Result will be
For your GET Aciton, It will print "
From GET
"After user submit's the form, It will print "
Totally new value
";If you want the previous view bag data to be posted, keep that in a hidden form field.
And your Action method, we will accept the hidden field value as well
Result will be
For your GET Aciton, It will print "
From GET
"After user submit's the form, It will print "
From GET-Totally new value
";Try to avoid dynamic stuff like ViewBag/ViewData for transferring data between your action methods and views. You should use strongly typed views and viewmodels models.