How can ViewBag data be saved after a form post?

Pittfall picture Pittfall · Jun 12, 2012 · Viewed 19.8k times · Source

So I have a ViewBag.Something and this data is randomly generated. In my view, I set this to a label like so @Html.LabelFor(m => m.Something, (string)ViewBag.Something). This works out well but when I submit the form there could be errors and if there are errors, I need this label to remain the same, I don't want dynamic/random data anymore so I wouldn't call the controller method that generated this ViewBag. Is there a way to retain this value without having some private variable in my controller? Some nice way that MVC/Razor does it?

Answer

Kapil Khandelwal picture Kapil Khandelwal · Jun 12, 2012

Option 1:

Pass the value of "ViewBag.Something" to the Controller by using route Values:

@Html.ActionLink("ButtonText", "ActionName", new { Something = @ViewBag.Something })

Option 2: You can use TempData.

public ActionResult Index()
{
 var Something = "YOURVALUE";
 TempData["Something"] = Something;
.......
}


public ActionResult OtherAction()
{
    var Something = TempData["Something "];
    ...........
}

Passing State Between Action Methods

Action methods might have to pass data to another action, such as if an error occurs when a form is being posted, or if the method must redirect to additional methods, as might occur when the user is directed to a login view and then back to the original action method.

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.