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?
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.
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.
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.
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.
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