Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 397
Bit_Pulse Avatar asked May 17 '14 12:05

Bit_Pulse


1 Answers

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);
            }
        });
    });
like image 183
Bit_Pulse Avatar answered Sep 29 '22 16:09

Bit_Pulse