jQuery Ajax: Reference MVC controller url from App root

前端 未结 2 1058
粉色の甜心
粉色の甜心 2021-01-05 06:54

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

相关标签:
2条回答
  • 2021-01-05 07:33

    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;
    }
    
    0 讨论(0)
  • 2021-01-05 07:43

    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")')

    0 讨论(0)
提交回复
热议问题