Monday, May 20, 2024
13
rated 0 times [  15] [ 2]  / answers: 1 / hits: 35717  / 13 Years ago, tue, may 31, 2011, 12:00:00

How can I store a value in the ViewBag accessing it from javascript?


More From » asp.net-mvc-3

 Answers
22

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>

[#91947] Monday, May 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;