11

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.

asked Sep 20, 2012 at 14:23

4 Answers 4

21

Url.Action is 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.Action helper 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

<script type="text/javascript">
 var yourApp = yourApp || {};
 yourApp.Urls = yourApp.Urls || {};
 yourApp.Urls.baseUrl = '@Url.Content("~")';
 yourApp.Urls.editUserUrl= '@Url.Action("Edit","User")';
</script>

Or in your page specific view,

@section Scripts
{
 <script type="text/javascript">
 var yourApp = yourApp || {};
 yourApp.Urls = yourApp.Urls || {};
 yourApp.Urls.baseUrl = '@Url.Content("~")';
 yourApp.Urls.editUserUrl= '@Url.Action("Edit","User")';
 </script>
 <script src="~/Scripts/PageSpecificExternalJsFile.js"></script> 
}

Now in your external javascript file, you can access it like

var urlToEditUser = yourApp.Urls.editUserUrl;
//you can use urlToEditUser now
// Or With the base url, you may safely add the remaining part of your url.
var urlToEditUser2 = yourApp.Urls.baseUrl+"User/Edit";
//you can use urlToEditUser2 now

Always use the Url.Action or Url.RouteUrl html 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.

answered Sep 20, 2012 at 14:36
Sign up to request clarification or add additional context in comments.

2 Comments

but is not writing js code to MVC view also a bad practice ? I
to get the Path to a global variable, It is fine. This is the only way you can get the path using the Helper method and pass to external js file.
7

You can't use '@Url.Action("SomeAction", "SomeController")' in js file, because this is ASP.NET MVC helper, if you put your code to the view everything will work.

Shimmy Weitzhandler
105k127 gold badges437 silver badges646 bronze badges
answered Sep 20, 2012 at 14:32

Comments

1

My approach is similar to @Shyju's, except instead of setting one variable in the Razor view, I call an init function in my JavaScript, and pass it all the parameters that I need interpreted by Razor.

So the code would look like this:

MyScript.init({
 editUserUrl: "@Url.Action("Edit","User")",
 anotherUrl: "@Url.Action("AnotherUrl", "User")"
})

Then in JavaScript:

var m_options;
MyScript.init = function(options) {
 m_options = options;
}
// use with m_options.editUserUrl here
$.ajax(
{
 type: "POST",
 url: m_options.editUserUrl,
 data: { 
 fileID: rightClickedFileId
 },
 success: function (data) {
 }
 });

I wrote a more detailed post about it here: http://blog.blanklabs.com/2015/02/aspnet-mvc-refactoring-friendly.html

answered Feb 1, 2015 at 23:58

Comments

1

you can write it like this way just

url:'/controllername/Actionname',
Håken Lid
23.2k10 gold badges58 silver badges73 bronze badges
answered Mar 31, 2017 at 10:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.