unknownUser
unknownUser

Reputation: 125

Access to viewbag using javascript code

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

Answers (3)

Phil
Phil

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

Daniel Elliott
Daniel Elliott

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

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

<script type="text/javascript">
    var yourVariable= @Html.Raw(Json.Encode(ViewBag.yourVariable))
</script>

Upvotes: 2

Related Questions