问题
I have an ASP.NET MVC web application running from http://localhost/myappname
. From jQuery, I make jQuery $.ajax() calls to return partial views based on some user action. I usually call this from a view in the same controller that contains the function I am calling via Ajax. For example, a view in my Home controller has the following function (which works well):
function loadMyPartialView() {
$.ajax({
type: 'GET',
url: 'Home/GetNavigationTreePV/',
success: function (data) { onSuccess(data); },
error: function (errorData) { onError(errorData); }
});
return true;
}
This above url gets resolved to http://localhost/myappname/Home/GetNavigationTreePV
and the partial view is returned correctly.
Now, I am trying to use qUint to unit test my functions. In this test case, I just want to verify I get to the end of the function and return true. I have created a QUNIT
controller and corresponding view (which loads my unit test JavaScript file). From the test.js file that contains my unit tests, I try to make calls to the same functions that are in my Home views, like the one above. But, since I am now running out of the QUNIT
controller, the url gets resolved to http://localhost/myappname/qunit/Home/GetNavigationTreePV
.
I have tried changing the url of my ajax request to /Home/GetNavigationTreePV/
(with the preceding forward slash), but when I do that I get the following url http://localhost/myappname/Home/GetNavigationTreePV
.
So, to be clear, I am trying to write my ajax request in a way that will always start from the root of my MVC application, and then append the url parameter given in my $.ajax() function.
Is there an easy way to do that? Am I going about this in a weird way?
回答1:
I think in your MVC View page you need @Url.Action
function loadMyPartialView() {
$.ajax({
type: 'GET',
url: '@Url.Action("GetNavigationTreePV", "Home")',
success: function (data) { onSuccess(data); },
error: function (errorData) { onError(errorData); }
});
return true;
}
Alternatively you can use @Url.Content
function loadMyPartialView() {
$.ajax({
type: 'GET',
url: '@Url.Content("~/home/GetNavigationTreePV")',
success: function (data) { onSuccess(data); },
error: function (errorData) { onError(errorData); }
});
return true;
}
If this is in a .js file, you can pass in the Url like
loadMyPartialView('@Url.Action("GetNavigationTreePV", "Home")')
回答2:
I was able to accomplish this with straight JavaScript using window.location.pathname
. See the following example:
function loadMyPartialView() {
$.ajax({
type: 'GET',
url: window.location.pathname + 'Home/GetNavigationTreePV/',
success: function (data) { onSuccess(data); },
error: function (errorData) { onError(errorData); }
});
return true;
}
来源:https://stackoverflow.com/questions/7713859/jquery-ajax-reference-mvc-controller-url-from-app-root