JQuery Ajax: Link MVC Controller URL from Application Root

I have an ASP.NET MVC web application running from http://localhost/myappname . From jQuery, I call jQuery $ .ajax () calls to return partial views based on some user actions. Usually I call this from a view in the same controller that contains the function that I call through Ajax. For example, the 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 url above gets permission http://localhost/myappname/Home/GetNavigationTreePV , and the partial view is returned correctly.

Now I'm trying to use qUint to unit test my functions. In this case, I just want to check, get to the end of the function and return true. I created a QUNIT controller and the corresponding view (which loads my unit test JavaScript file). From the test.js file that contains my unit tests, I am trying to make calls with the same functions as in my Home views, for example, above. But, since I have exhausted the QUNIT controller QUNIT , the url gets permission http://localhost/myappname/qunit/Home/GetNavigationTreePV .

I tried changing the url of my ajax request to /Home/GetNavigationTreePV/ (with the previous slash), but when I do this, I get the following url http://localhost/myappname/Home/GetNavigationTreePV .

So, to be clear, I'm trying to write my ajax request in a way that will always start at the root of my MVC application, and then add the url parameter specified in my $ .ajax () function.

Is there an easy way to do this? Am I going about this in a weird way?

+7
source share
2 answers

I was able to accomplish this using direct 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; } 
+10
source

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 it is a .js file, you can pass it to a URL like

loadMyPartialView ('@ Url.Action ("GetNavigationTreePV", "Home")')

+10
source

All Articles