jQuery AJAX works to return mvc 3 partial view but jQuery load doesn't

拜拜、爱过 提交于 2019-12-04 05:21:33

问题


I'm trying to populate a div with a partial view in MVC 3. My controller looks like this:

[HttpPost]
public ActionResult GetCustomerList(string searchString)
{
    var custService = new CustomerViewModels();
    var custListVM = custService.GetSearchList(searchString);

    return PartialView("GetCustomersList", custListVM);
}

and my jQuery call looks like this:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        async: false,
        data: { searchString: searchCriteria },
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

It works fine. I began to wonder if I could use the jQuery load method to do the same thing with a lot less code and wrote this:

function getCustomerList(searchCriteria) {
    $("#customerTabBody").load('Home/GetCustomerList', { searchString: searchCriteria });
};

It returns an error saying the resource can't be found. I've tried using @Url.Action but it encodes the same controller path I have hard coded. In Firebug I can see that the URL that is being posted to is the same and the searchString parameter is identically formatted in both instances.

What's the difference - why does load not work?

Thanks


回答1:


Jquery docs for load says...

The POST method is used if data is provided as an object; otherwise, GET is assumed.

since you are passing data as an object, it has to be a post call according to docs. Furthermore, you are getting required data from controller through $.ajax so controller action method seems to be alright. There may be some error when sending the ajax request using load. you can inspect this in firebug.




回答2:


Can you try this to see if it works?

function getCustomerList(searchCriteria) {

         $('#customerTabBody').load('@Url.Action("GetCustomerList", "Home")', { 'searchString': searchCriteria });

};



回答3:


I'm fairly certain your .load() call executes a GET request rather than a POST. MVC 3 and most other .NET AJAX transactions (methods decorated as a WebMethod, such as web services and page methods) require data to be POSTed. In this case you'll simply need to stick with what works. As you can see in your working $.ajax() call, the request method is a POST. If you want to short-hand some of the code, use .ajaxSetup() combined with .post().



来源:https://stackoverflow.com/questions/6811625/jquery-ajax-works-to-return-mvc-3-partial-view-but-jquery-load-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!