How can I store a value in the ViewBag accessing it from javascript?
Asked
Active
Viewed 3.6k times
2 Answers
40
You cannot store a value in ViewBag from javascript. ViewBag is a server side concept and exists only on the server. Javascript runs on the client. As far as storing some data from ViewBag into a javascript variable is concerned you could use the following:
<script type="text/javascript">
var foo = @Html.Raw(Json.Encode(ViewBag.FooBar))
</script>
Now this being said I always advice people against using ViewBag/ViewData in ASP.NET MVC. I recommend using strongly typed view and view models. So your code will look like this:
@model MyViewModel
<script type="text/javascript">
var foo = @Html.Raw(Json.Encode(Model))
</script>

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
1@Agzam, where do you want to access this object? In javascript? That's bad. That would mean that your views would be pulling information from some parts. Views are not supposed to pull information. They are supposed to use information that is being passed to them as view model from the controller action. So feel free to define a view model, a controller action that will fetch the information from wherever it is stored (Application scope in your case) and pass this view model to the view. Then inside this view all you have to do is use the view model => that's all that views should do – Darin Dimitrov May 31 '11 at 20:14
-
Now if you want to pass some information stored in a javascript variable to your server you have couple of possibilities: AJAX, HTML forms, window.location.href, anchors, ... – Darin Dimitrov May 31 '11 at 20:16
-
@DarinDimitrov - I'm just learning to switch from Web Forms to MVC and probably used about 20 of your answers lately , this one definetly saved me a lot of time – Scott Selby Dec 08 '12 at 04:44
3
You can't. ViewBag is a server-side thing, Javascript runs on client side.

Vilx-
- 104,512
- 87
- 279
- 422