7

所以我有一个完整的方法,我在整个网站上都使用它:

public PartialViewResult GetBlogEntries(int itemsToTake = 5)
{
    ...
    return PartialView("_BlogPost", model);
}

现在我想从我的 javascript 中以 JSON 形式获取它。

public JsonResult GetBlogPostJson()
{      
    var blogEntry = GetBlogEntries(1);
    var lastEntryId = GetLastBlogEntryId();
    return Json(new {Html = blogEntry, LastEntryId = lastEntryId}, JsonRequestBehavior.AllowGet);
}

想法是这样得到它:

$.ajax({
            url: '/Blog/GetBlogPostJson',
            dataType: 'json',
            success: function (data) {
                var lastEntryId = data.LastEntryId;
                var html = data.Html;
                ...
            }
        }); 

问题是这当然不会产生一个字符串,而是一个 PartialViewResult。

问题是,如何将 PartialViewResult 解析为可以用 JSON 发回的 html?

4

1 回答 1

16

我大约在 6 个月前经历过这个。目标是使用部分填充 jquery 弹出对话框。

问题是视图引擎想要以自己尴尬的顺序渲染它们......

试试这个。LMK 如果需要澄清。

    public static string RenderPartialViewToString(Controller thisController, string viewName, object model)
    {
        // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way)
        thisController.ViewData.Model = model;

        // initialize a string builder
        using (StringWriter sw = new StringWriter())
        {
            // find and load the view or partial view, pass it through the controller factory
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw);

            // render it
            viewResult.View.Render(viewContext, sw);

            //return the razorized view/partial-view as a string
            return sw.ToString();
        }
    }
于 2013-03-23T15:30:15.500 回答