Reputation: 125
I use aspx c# as a viewengine within ASP.NET mvc project, I want to retrieve value from viewbag using javascript code.
Upvotes: 4
Views: 13881
Reputation: 2181
If you are dealing with something simple like a string, you can save a viewbag in an data-* attribute of a HTML tag and use JavaScript to access that.
Upvotes: 0
Reputation: 22857
I get all my viewbag related stuff from in a razor view like so ...
<script>
var myJSVariable = @Viewbag.MyViewbagVariable;
</script>
You could do the following for the MVC view engine pre-razor I believe
<script>
var myJSVariable = <%Viewbag.MyViewbagVariable%>;
</script>
Upvotes: 5
Reputation: 26727
<script type="text/javascript">
var yourVariable= @Html.Raw(Json.Encode(ViewBag.yourVariable))
</script>
Upvotes: 2