I am doing an ajax “Post” action and i need to work out the URL of my action.
To do this i am using
var url = '<%= Url.Action("Action", "Controller") %>';
But this code lives in a rather large Js file that is loading into my MVC View. I dont want to move it all into my view as it is too big and will look a mess.
I tried setting my JS include to runat=”server” but this errors.
<script runat="server" src="<%: ResolveUrl("~/Scripts/Custom/MyScript.js")%>" type="text/javascript" ></script>
Can this be done?
Thanks,
Kohan
No you can’t put ASP.NET in a javascript file. Javascript files are static resources which should be directly served by your web server. They should never contain any server side language. You could define
urlas a global variable in the view:then use this
urlvariable in your javascript file.Notice tough that depending on what you are doing with this variable there might be much better ways. For example let’s suppose that in your view you have an anchor that you want to ajaxify:
Then in your javascript you could:
So no need of declaring any variables at all. Another option is to define a javascript function which takes parameters so that you can pass it whatever you need.
Conclusion: think of your javascript files as reusable components that tomorrow you might plug into your cool site based on Java Servlets for example and host them on a CDN. You could even try to convert them to reusable jQuery plugins. Don’t try to mix it with server side languages as it leads to a strong coupling, ugly code – tag soup.