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?
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
.cshtmlview file.Option Two:
Create a JavaScript function that accepts the url as a param and call it from the view: