Reputation: 640
I have mvc4 webpage where I have a @Html.TextBox()
@Html.TextBox("searchString", null, new { id = "searchingForProject" })
This textbox has a keyup
listener, that will start an ajax search for projects, and update the view if the result is a success
var timeoutReference;
var timeoutforloading;
$(function () {
$("#searchingForProject").keyup(function () {
timeoutReference = setTimeout(function () {
timeoutforloading = setTimeout(function () {
$("#imageWebGridLoad").show();
$("#gridcontent").hide();
}, 250);
var value = $("#searchingForProject").val();
$.ajax({
url: '@Url.Action("Index", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('projects').html(result);
clearTimeout(timeoutforloading);
});
}, 750);
});
});
The problem is, that this function works just fine, if it is placed within a internal <script>
, but if it is placed in an external javascript file, it will not give me any results.
I know it calls the function, as the $("#imageWebGridLoad").show();
will start spinning after 0.25 seconds.
Is it something in my Ajax call that's wrong, or is it not possible to do it in an external js file like this?
Upvotes: 2
Views: 1065
Reputation: 22084
The @Url.Action("Index", "Project") gets replaced with real url only in view file. Declare it as variable in your view file.
<script>
var sUrl = '@Url.Action("Index", "Project")';
</script>
and call sUrl from external .js file.
$.ajax({
url: sUrl,
...
EDIT:
Another way around would be to serve your original js through view like.
<script src="@Url.Action("Index", "ExternalJS")"></script>
and put "ExternalJS" method on Index controller to serve the view with your original javascript.
Upvotes: 1
Reputation: 63550
I don't use MVC4, but my guess is that now the JS is external, the ASP isn't translating @Url.Action("Index", "Project")
to an actual URL for use with the AJAX. I believe that if you have this information as a hidden div
in your HTML and then call that in with a jQuery selector, you will be able to use it like you want:
// HTML
<div id="ajaxurl" class="hidden">@Url.Action("Index", "Project")</div>
// JS
$.ajax({
url: $('#ajaxurl').text(),
// ...
})
or (thanks Satpal)
// HTML
<div id="ajaxurl" class="hidden" data-url='@Url.Action("Index", "Project")'></div>
// JS
$.ajax({
url: $('#ajaxurl').data('url'),
// ...
})
Upvotes: 5