i have written a jquery functions in external JS file and included that file where ever i required.
In jquery function i called action method from my controller. Now my problem is i’m not able to locate that action method path from the external JS. It is throwing error that is method not found like that.
Now how i can write the action path name in the external JS which will work from any where.
I tried following for mentioning/calling action method –
1. url: "/Employee/AutocompleteSuggestions"
2. url: "AutocompleteSuggestions"
3. @Html.Raw(Url.Action("AutocompleteSuggestions", "Employee", new { @term = "Term", @moduleName="ModuleName"}))
3rd is not working because of razor syntax.
How to resolve this problem ?
I used the JS like below –
$.ajax({
url: "AutocompleteSuggestions",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data:
JSON.stringify({
term: request.term,
moduleName: "Employee"
}),
success: function (data) {
response($.map(data, function (item) {
return { label: item.FullName, value: item.Id }
}
))
},
error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }
})
One issue you have here is that you will probably need to use a global; which could be vulnerable to script attacks. See my original answer for the most naive implementation.
I think this is probably pretty safe – but there are much better Javascript gurus out there who might have a better answer.
In your layout/master you can just output a script block like this (I’m using Razor):
And then include your script after that, using something like this:
When you need to use that URI in your script (just demonstrating here with a jQuery Get).
In response to your comment on @David’s answer
Sure; you can use Razor to output the JS: Just write a controller action that fires a Razor view which returns javascript (although you’ll have to do a little mucking around with the response types) but if you do this you lose all caching/compression benefits on that script and then you have to write that all back in again.