Pulse Pulse - 14 days ago 7
jQuery Question

MVC3: jquery ajax to return partial view with HTML dataType from controller but getting error

I need some help. I am returning partial view as HTML dataType from controller action when calling it from jQuery ajax on button click event.

This is my Javascript tag from my main view:

$(function () {
$('#searchButton').click(function () {
var DTO = {
Name: $('#Name').val()
};
$.ajax({
url: '/Grid/GetSearch',
type: "GET",
dataType: "html",
data: DTO,
cache: false,
success: function (data) {
//Fill div with results
$("#SearchViewDiv").html(data);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
});
});


Controller code:

[HttpGet]
public ActionResult GetSearch(string name)
{
var accounts = _userAccounts.FindAll(x => x.Name.Contains(name));
return PartialView("SearchResult", accounts);
}


I am able to debug this controller when jQuery ajax is making call to this action but when it is returning I am getting into error function of jQuery Ajax. So guessing target URL is correct. But not able to figure out where I am going wrong. Please let me know if more info is required.

Answer

Thanks Dzmitry for your inputs. But I figured out the solution.

Issue: Problem was page was reloading after button click that was causing Ajax call to be getting cancelled while returning this partial view response.

Solution: Just adding event.preventDefault() solved this problem. So Javascript snippet will look like this,

$('#searchButton').click(function (e) {
        var DTO = {
            Name: $('#Name').val()
        };
        e.preventDefault();
        $.ajax({
            url: '/Grid/GetSearch',
            type: "GET",
            dataType: "html",
            data: DTO,
            cache: false,
            success: function (data) {
                //Fill div with results
                $("#SearchViewDiv").html(data);
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    });