ASP.NET MVC using ViewData in javascript

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;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)