4

I use aspx c# as a viewengine within ASP.NET mvc project, I want to retrieve value from viewbag using javascript code.

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

3 Comments

I use aspx c# as a viewengine
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?
Beware of single quotes in your variables: stackoverflow.com/a/10389766/2550529
2
<script type="text/javascript">
    var yourVariable= @Html.Raw(Json.Encode(ViewBag.yourVariable))
</script>

1 Comment

I use aspx c# as a viewengine
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.