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

前端之家收集整理的这篇文章主要介绍了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和其他视图数据。

原文链接:https://www.f2er.com/aspnet/254086.html

猜你在找的asp.Net相关文章