How to Access ViewData in javascript

28,154

Solution 1

Try adding some quotes around the output:

var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);

Edit:

I notice you're using NAME for the key; could this name ever have a single quote in it? If it's possible that any value will ever contain one, you will want something like this instead so your page doesn't break again (although technically this seems to be more of a job for the controller or model):

var test = '<%= ViewData["NAME"].ToString().Replace("'", "\\'") %>';
alert(test);

Solution 2

try

var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);

(notice the quotes around <%= %>)

Share:
28,154
Billy Logan
Author by

Billy Logan

Updated on March 04, 2020

Comments

  • Billy Logan
    Billy Logan about 4 years

    I am having a problem accessing the ViewData object through javascript.

    I have set the ViewData object on the controller and on document.ready event of the view i am trying to see the contents of that same ViewData object like so:

         var test = <%= ViewData["NAME"].ToString() %>;
         alert(test);
    

    I don't get an alert message after this and none of my script after this statement will run. I am assuming this script is invalid thus killing everything afterwards. I have tried a few different variations of this same script without any luck.

    What am i missing here?

    Thanks in advance, Billy

  • Billy Logan
    Billy Logan about 14 years
    You got it. Wonder why the examples i saw didn't have those quotes. Thanks.
  • Billy Logan
    Billy Logan about 14 years
    Thanks for the response, John just barely beat you to it. Did give you a mark as well though.
  • digawp
    digawp almost 9 years
    I think the examples you saw assumed that you write your scripts in the View file directly (i.e. within <script> tags) which is why it will work without the surrounding quotes.