ASP.NET MVC将部分视图呈现为要使用JSON返回的字符串

Pat*_*ick 7 javascript c# asp.net-mvc jquery asp.net-mvc-4

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

public PartialViewResult GetBlogEntries(int itemsToTake = 5)
{
    ...
    return PartialView("_BlogPost", model);
}
Run Code Online (Sandbox Code Playgroud)

现在我想从JSON格式的javascript中获取此信息.

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

想法就是这样:

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

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

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

Dav*_*ich 16

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

问题是View Engine想要以它自己的尴尬顺序渲染它们......

试试这个.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();
        }
    }
Run Code Online (Sandbox Code Playgroud)