Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for passing data from asp.net-mvc to javascript

I've been working with ASP.NET MVC and Javascript/jQuery a lot lately and I seem to be heading in a direction where I'm always needing to pass some dynamic value "to" my javascript. When the script is right in the page, I've done something like this:

var isEditable = <%=ViewData["editable"]%> 

I like how this is quick & easy and just like I'd inject a value into HTML. But this smells. Really, really bad. And it breaks Visual Studio's intellisense and code formatting, making my scripts hard to read and understand.

It has occurred to me another solution would be to pass my data to a hidden field, and have the Javascript reference that...

<input type="hidden" id="editable" value="<%=ViewData["editable"]%>" /> var isEditable = $("#editable").attr("value"); 

This is probably much better as it keeps the script intact and would allow me to move it to an external .js file. But something about this solution doesn't seem ideal either. Or is it just me?

Can anyone recommend solutions & best practices for passing data into your scripts? Am I headed down the wrong path if my scripts end up heavily relying the viewdata from my controllers in the first place?

like image 483
Kurt Schindler Avatar asked Jul 28 '09 22:07

Kurt Schindler


People also ask

How pass value to JavaScript function in MVC?

You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter.

What are the way of passing data in ASP NET MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can ASP NET MVC use JavaScript?

JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.


1 Answers

I sometimes pass data to my pages by writing a config object to the page via a JSON serializer:

var pageConfig = <%= ServerConfig.ToJson() %>; 

Where you need to write the ToJson method yourself. This keeps the page state nicely contained, so that there is only one place where you inject server values. Everything from here on out is pure javascript. In your example, you could then do:

var isEditable = pageConfig.isEditable; 

even in an external js file, if pageConfig is global. In that case, though, you should properly namespace it: MY_APP.pageConfig perhaps.

like image 113
Gabe Moothart Avatar answered Oct 08 '22 16:10

Gabe Moothart