I am trying to use Url.Action() method in my js file to define urls for my ajax calls. So far I have failed.
$.ajax(
{
type: "POST",
url: '@Url.Action("SomeAction", "SomeController")',
data: {
fileID: rightClickedFileId
},
success: function (data) {
}
});
If i define the url in this way, browser tries to post data to
http://localhost:5907/FileManager/@Url.Action(%22SomeAction%22,%20%22SomeController%22)
and as a result my ajax call fails.
However, If I use '/SomeController/SomeAction' instead, everythings works fine.
Second works ok, but I am wondering the problem with first one ? Could it be due to routing configuration ?
Thanks.
Url.Actionis an html helper method which will work in your razor view, not in your external javascript files.What you can do is, get the relative url to your action method using
Url.Actionhelper method in a razor view and set that to a javascript variable and use that in your external js file. When doing this, Always make sure to use javascript namespacing to avoid possible conflict with existing global variables.You may add this code in the _Layout.cshtml
Or in your page specific view,
Now in your external javascript file, you can access it like
Always use the
Url.ActionorUrl.RouteUrlhtml helper methods to build the relative url to the action methods. It will take care of correctly building the url regardless of your current page/path.If you want to do the same thing inside your angular controller’s/data services etc, take a look at this post which explains how to use the angular value provider to do the same.