asp.net-mvc – 如何渲染部分视图到字符串

我有以下代码:

public ActionResult SomeAction()
{
    return new JsonpResult
    {
        Data = new { Widget = "some partial html for the widget" }
    };
}

我想修改它,以便我可以有

public ActionResult SomeAction()
{
    // will render HTML that I can pass to the JSONP result to return.
    var partial = RenderPartial(viewModel); 
    return new JsonpResult
    {
        Data = new { Widget = partial }
    };
}

这可能吗?有人能解释一下吗?

注意,我在发布解决方案之前编辑了问题。

我选择了像ASP.NET MVC 4应用程序的扩展方法如下。我认为它比我看到的一些建议更简单:

public static class ViewExtensions
{
    public static string RenderToString(this PartialViewResult partialView)
    {
        var httpContext = HttpContext.Current;

        if (httpContext == null)
        {
            throw new NotSupportedException("An HTTP context is required to render the partial view to a string");
        }

        var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();

        var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory().CreateController(httpContext.Request.RequestContext, controllerName);

        var controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller);

        var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View;

        var sb = new StringBuilder();

        using (var sw = new StringWriter(sb))
        {
            using (var tw = new HtmlTextWriter(sw))
            {
                view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw);
            }
        }

        return sb.ToString();
    }
}

它允许我执行以下操作:

var html = PartialView("SomeView").RenderToString();

此外,此方法仍然保留视图的任何Model,ViewBag和其他视图数据。

http://stackoverflow.com/questions/2537741/how-to-render-partial-view-into-a-string

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:asp.net-mvc – 如何渲染部分视图到字符串