31

I am currently building a website in ASP.NET MVC. I am trying to access ViewData in javascript.

Is there any way that I can access a string value using javascript in a View that was stored in ViewData in a Controller Action. ( I am not able to figure out the right syntax ).

I wish to do something like..


var str = ViewData["Text"];

I tried the following:

var str = <%=ViewData["Text"] %>

but it didn't work.

Can someone please help.

Thanks.

Jake
  • 16,329
  • 50
  • 126
  • 202

2 Answers2

61

Like this (Razor):

var str = @Html.Raw(Json.Encode(ViewData["Text"]));

or (WebForms), using the JavaScriptSerializer (and after importing theproper namespace to your webform - System.Web.Script.Serialization):

var str = <%= new JavaScriptSerializer().Serialize(ViewData["Text"])) %>;

And please don't use ViewData in an ASP.NET MVC application. Use view models and strongly typed views so that your code looks like this:

var str = <%= new JavaScriptSerializer().Serialize(Model.Text) %>;

This technique is even cooler as now you can JSON serialize the entire view model:

var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
var str = model.Text;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
10

That should be:

var str = '<%= ViewData["Text"] %>';
Dave Ward
  • 59,815
  • 13
  • 117
  • 134
  • 5
    No, that's very bad. Never use something like this in a real world application. What if the text contains a quote? This code is pretty vulnerable to XSS attacks especially if this Text comes from user input. – Darin Dimitrov May 02 '11 at 22:21
  • 1
    He was *so* close already, I thought it would be more helpful to answer the question he had than make it over-complicated. – Dave Ward May 02 '11 at 22:29
  • 10
    this is not an answer to the question!!! This is an invitation to XSS attacks and advertising bad practices. We are not talking about over-complicating here. We are talking about answering the question. How can you possible say that this answers the question? I mean this code will break soon and it will be subject to yet another question on SO. I can't believe that this question was upvoted and you haven't deleted it yet so that it doesn't get indexed as someone might actually use this in his application. – Darin Dimitrov May 02 '11 at 22:31
  • 1
    Your answer is clearly more widely applicable. Given your comments here and in your own answer, I'm sure he'll understand to encode and escape if he expects apostrophes or user-generated data in his ViewData. I also believe that him seeing what was wrong with his own, more simple code is valuable. – Dave Ward May 02 '11 at 22:45
  • 3
    I agree. Darin's is the proper answer - but it's good to know the other (albeit "not recommended") way too. +1 to both of you. – RPM1984 May 03 '11 at 03:25