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.
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.
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.
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.
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).
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;
That should be:
var str = '<%= ViewData["Text"] %>';
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