简体   繁体   中英

partial view c# using ajax

I'm trying to return from controller partial view using ajax while debugging I see that the correct data is sent to the controller but when the controller finished to do what his need he moved automaticaly to function Dispose instead to return the partial view

The code in the controller is:

    public PartialViewResult SearchPosts(string keyword)
    {
        var data = db.Posts.Where(f => f.Title.Contains(keyword) || f.Author.Contains(keyword)).ToList();
        return PartialView("_SearchPostsPArtial", data);
    }

and partial code from the View is:

    $(document).ready(function () {
        $('#buttonSearch').click(function () {
            var keyword = $('#searchAjax').val();
            $.ajax({
                url: '@Url.Action("SearchPosts", "Posts")',
                contentType: 'application/html; charset=utf-8',
                type: 'GET',
                data: { keyword: keyword },
                dataType: 'html'
            })
            .success(function (result) {
                $('#result').html(result);
            })
            .error(function (xhr, status) {
                console.debug(status);
            })
        });
    });

Normal scenario on using ajax is return data in global string formats (specially in j-son format), Why you want to use partial-view returned action for that? If you need this partial view anyway I suggest write another action to response to your ajax call and if your action does many code you could split it to tow method and call the main section in partial-view and ajax-response actions, pseudo code could be like this:

private GetData([parameters...])
{
  ...
  code to get proper data
  ...
}
public PartialViewResult SearchPosts(string keyword)
{
  [DataType] data = GetData([variables...]);
  return PartialView("_SearchPostsPArtial", data);
}

public JsonResult SearchPosts(string keyword)
{
  [DataType] data = GetData([variables...]);
  return Json(data);
}

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM