Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access ViewData in javascript

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

like image 234
Billy Logan Avatar asked Mar 03 '10 20:03

Billy Logan


People also ask

How do I access ViewData?

You can now access ViewData["students"] in the view, as shown below. Above, we retrieve the value using ViewData["students"] and typecast it to an appropriate data type. You can also add KeyValuePair objects into the ViewData, as shown below. ViewData and ViewBag both use the same dictionary internally.

Can JavaScript access ViewBag?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor. In this article I will explain with an example, how to access value of ViewBag object inside JavaScript function in ASP.Net MVC Razor.

How do I pass a ViewBag in JavaScript?

var c = "#" + "@ViewBag.CC"; var d = $("#" + "@ViewBag.CC"). value; var e = $("#" + "@ViewBag.CC"). val(); var c = "@ViewBag.CC"; var d = $("@ViewBag.CC").

Can we use ViewData in jQuery?

ViewData is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery.


2 Answers

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);
like image 145
John Rasch Avatar answered Sep 17 '22 13:09

John Rasch


try

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

(notice the quotes around <%= %>)

like image 38
Marek Karbarz Avatar answered Sep 17 '22 13:09

Marek Karbarz