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
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.
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.
var c = "#" + "@ViewBag.CC"; var d = $("#" + "@ViewBag.CC"). value; var e = $("#" + "@ViewBag.CC"). val(); var c = "@ViewBag.CC"; var d = $("@ViewBag.CC").
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.
Try adding some quotes around the output:
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);
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);
try
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);
(notice the quotes around <%= %>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With