Return Partial View As JsonResult

风格不统一 提交于 2019-12-13 19:06:55

问题


I have a partial view that returns an HTML chunk of list items that gets appended onto an unordered list via an AJAX call. This all works fine.

However, once I receive the HTML back from the AJAX call, I would like to be able to set some properties on each of the list items via JQuery. In order to do that, I'm assuming that I need to receive the results of that AJAX call back as a JsonResult rather than a ActionResult. Unfortunately, I want to keep using the ASCX that I'm using to render the HTML since it has quite a bit of formatting data contained within it.

Is it possible to render a partial view and then convert it to a JsonResult for the AJAX client or is there a different approach that I should consider?

Any advice is much appreciated.

Thanks!


回答1:


You dont actually need a JsonResult. A partial that is an ActionResult retrieves some xml/html right? Then you can use jquery to parse it and query it like this:

function success(result) {
    var html = $(result); //this creates a jquery object out of your result html
    $("ul li", html); //this gets you all the list items in context of the resulting html
}

Also if your result is just a bunch of lis then you can do this:

function success(result) {
    var lis = $(result);
    lis.each(function() { $(this).append(" testing"); });
    $("#yourUl").append(lis);
}

This can be simplified with chaining but i made it a bit more verbose so its easier to understand



来源:https://stackoverflow.com/questions/1330959/return-partial-view-as-jsonresult

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