Maintaining ViewBag values while posting data

mmushtaq picture mmushtaq · Dec 11, 2015 · Viewed 14.4k times · Source

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";

Answer

Shyju picture Shyju · Dec 12, 2015

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

public ActionResult Create()
{
  ViewBag.Message = "From GET";
  return View();
}
[HttpPost]
public ActionResult Create(string someParamName)
{
  ViewBag.Message = ViewBag.Message + "- Totally new value";
  return View();
}

Assuming your view is printing the ViewBag data

<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
  <input type="submit" />
}

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.

<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
  <input type="hidden" value="@ViewBag.Message" name="Message" />
  <input type="submit" />
}

And your Action method, we will accept the hidden field value as well

[HttpPost]
public ActionResult Create(string someParamName,string Message)
{
  ViewBag.Message = ViewBag.Message + "- Totally new value";
  return View();
}

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.