Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  197] [ 1]  / answers: 1 / hits: 73939  / 13 Years ago, mon, may 2, 2011, 12:00:00

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.


More From » asp.net-mvc

 Answers
28

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;

[#92446] Friday, April 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;