1

I have an MVC app which has a home controller with the method GetResult in it:

public int GetResult()
        {
            return 3;
        }

I call it in a javascript file using:

$.post('/Home/GetResult', null, function (data) {

        alert(data);

    });

and it works fine.

However I tried to use a none hardcorded way of calling it

$.get('@Url.Action("GetResult", "Home")', null, function (data) {

        alert(data);

    });

It's not working I'm getting a 500 errir.

It's trying to get to the URL:

http://localhost:xx/Home/@Url.Action(%22GetResult%22,%20%%22Home%22)

Well this is obviously isn't right.

Anyone know what I'm doing wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
AnonyMouse
  • 18,108
  • 26
  • 79
  • 131

2 Answers2

2

You cannot use Razor syntax inside a JavaScript file. Razor is a server-side scripting construct that needs to be parsed by ASP.Net to function.

You have two options:

Option One:

Move the script into the .cshtml view file.

Option Two:

Create a JavaScript function that accepts the url as a param and call it from the view:

function foo(posturl){
    $.post(url, null, function (data) {
        alert(data);
    });
}

/* View */
foo('@Url.Action("GetResult", "Home")');
Alex
  • 34,899
  • 5
  • 77
  • 90
0

It works on Razor views only.If you want to access it on a exteranl javascript file, You may get the Path name using the HTML Helper method in a razor view and Keep that in a Global java script variable and access that in the external javascript file

in your View,

<script type="text/javascript>
  var globalGetResultPath='@Url.ACtion("GetResult","Home)';
</script>

And in the external script now you can call like

$.get(globalGetResultPath, function (data) {
    alert(data);
});
Shyju
  • 214,206
  • 104
  • 411
  • 497