I use aspx c# as a viewengine within ASP.NET mvc project, I want to retrieve value from viewbag using javascript code.
3 Answers
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>
3 Comments
unknownUser
I use aspx c# as a viewengine
paaone
When I tried the above method, it said "Conditional compilation turned off" and it wouldn't work. I tried looking up for solutions for that and I one of the solutions was Add /*@cc_on @*/ in your code. stackoverflow.com/a/6655726/620337> It comments out all the code after it irrespective of where I add it. Is there something I am overlooking?
SepehrM
Beware of single quotes in your variables: stackoverflow.com/a/10389766/2550529
<script type="text/javascript">
var yourVariable= @Html.Raw(Json.Encode(ViewBag.yourVariable))
</script>
1 Comment
unknownUser
I use aspx c# as a viewengine