Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC using ViewData in javascript

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.

like image 890
Jake Avatar asked May 02 '11 22:05

Jake


People also ask

What is ViewData in ASP NET MVC?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary.

Can we access TempData in JavaScript?

The value of the TempData will be read using Razor Syntax in JavaScript and the value will be displayed in JavaScript Alert Message Box. In this article I will explain with an example, how to read (get) value of TempData using JavaScript in ASP.Net MVC Razor.

How do you pass data from view to controller in MVC using ViewData?

ViewData itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.

When should we use ViewData?

All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).


2 Answers

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; 
like image 199
Darin Dimitrov Avatar answered Sep 23 '22 17:09

Darin Dimitrov


That should be:

var str = '<%= ViewData["Text"] %>'; 
like image 36
Dave Ward Avatar answered Sep 21 '22 17:09

Dave Ward