Question

I am using Viewbags as a way to hold dynamic values in a textbox inside my Ajax.forms; would there be a danger of viewbags expiring or losing they're value like a Session variable? This is my simple form

@using (Ajax.BeginForm("mydownloads", "mycontroller", null, new AjaxOptions
{
UpdateTargetId = "globe",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post"
}))
{
@Html.TextBox("firstname", (object)@ViewBag.firstname)
@Html.TextBox("lastname", (object)@ViewBag.lastname)
<input type="search" id="post" />
}

As you can see this does submit but its done via Ajax. I have had bad experiences with Session variables as they tend to expire with out warning could something like that happen with a ViewBag?

Was it helpful?

Solution

No, there aren't any dangers of losing values stored in ViewBag. Any value that a controller action writes to the ViewBag is absolutely guaranteed to be available in the corresponding view. The ViewBag is a short-living object store to transport values from the controller action to the view.

Personally I find it very bad practice to use as it is weakly typed. I always prefer to use a strongly typed view model whenever I need to pass some information from a controller action to the view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top