Referencing MVC Actions in Javascript

by EvanJPalmer


How do you access an MVC endpoint from some Javascript code?

One way to do it would be to just manually resolve the URL of your endpoint and hardcode it:

var url = '/Home/GetFeeForOrder';
// perform a get on this URL

I don’t like this too much. Mainly because string literals like that scare me. I mean, things change and it makes leaning on the IDE tools to find references much harder.

I use a different pattern in which I let the Framework resolve the path and put it in a data attribute. I then access the data attribute from the JS file. For example:


<div id="order" data-fee-url="@Url.Action("GetFeeForOrder", "Home")">


Javascript file:

var url = $('#order').data().feeUrl;
// perform a get on this URL

I think this is nicer, as we no longer have the magic string. It also means that any route changes will automatically work and when I use visual studio to find all references, I’ll get more accurate results. It also cuts down on any human error when writing URL – granted, that’s something that would be evident quite quickly.

I’ve been told this method is convoluted, and I do admit, it’s is a little more time consuming than just writing the URL, but think this is outweighed by the benefits.