How to access ViewData in javascript

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

I set the ViewData object on the controller and in the document.ready event of the view. I am trying to see the contents of the same ViewData object as follows:

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

After that, a warning message does not appear, and none of my script will run after this statement. I assume this script is not valid, thus killing everything afterwards. I tried several different variations of the same script with no luck.

What am I missing here?

Thanks in advance, Billy

+4
source share
2 answers

Try adding some quotes around the output:

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

Edit:

I noticed that you are using NAME for the key; could this name ever have one quote in it? If it is possible that some value will ever contain one, you will want something similar instead, so that your page does not break again (although technically this seems to be more suitable for the controller or model):

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

to try

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

(note the quotes around <%= %> )

+5
source

Source: https://habr.com/ru/post/1303045/


All Articles