MVC 5渲染视图到字符串

时间:2014-05-06 12:28:34

标签: asp.net-mvc asp.net-mvc-5

看来,用于将视图呈现为字符串的大多数代码在MVC 5中都不起作用。

我有最新的MVC 5.1.2模板,我正在尝试将视图呈现为字符串。

    public static String RenderViewToString(ControllerContext context, String viewPath, object model = null)
    {
        context.Controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindView(context, viewPath, null);
            var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(context, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

嗯,它正在运行,但它的输出包含许多$标记而不是标记。我读过一些关于它的内容已在RC版本中修复,但那是旧闻。

问题看起来像这样

<$A$><h1></h1> 
<table</$A$><$B$> class=""</$B$><$C$>> <tbody</$C$><$D$></$D$><$E$>></tbody>
</table></$E$>

我想问一下,如何在最新的MVC 5模板中将视图呈现为字符串? 感谢。

5 个答案:

答案 0 :(得分:29)

好的,我似乎找到了解决方案。这个想法的作者是亚基尔庄园。

class FakeController : ControllerBase
{
    protected override void ExecuteCore() { }
    public static string RenderViewToString(string controllerName, string viewName, object viewData)
    {
        using (var writer = new StringWriter())
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController());
            var razorViewEngine = new RazorViewEngine();
            var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
            razorViewResult.View.Render(viewContext, writer);
            return writer.ToString();

        }
    }
}

这是假上下文和响应的技巧。

示例:

String renderedHTML = RenderViewToString("Email", "MyHTMLView", myModel );

我的文件MyHTMLView.cstml存储在Views / Email / MyHTMLView.cshtml中。电子邮件是一个虚假的控制器名称。

答案 1 :(得分:5)

以下是适用于MVC5上的会话和区域的解决方案。

public class FakeController : ControllerBase
{
    protected override void ExecuteCore() { }
    public static string RenderViewToString(string controllerName, string viewName,string areaName, object viewData,RequestContext rctx)
    {
        try
        {
            using (var writer = new StringWriter())
            {
                var routeData = new RouteData();
                routeData.Values.Add("controller", controllerName);
                routeData.Values.Add("Area", areaName);
                routeData.DataTokens["area"] = areaName;

                var fakeControllerContext = new ControllerContext(rctx, new FakeController());
                //new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController());
                fakeControllerContext.RouteData = routeData;

                var razorViewEngine = new RazorViewEngine();

                var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

                var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);

                razorViewResult.View.Render(viewContext, writer);
                return writer.GetStringBuilder().ToString();
                //use example
                //String renderedHTML = RenderViewToString("Email", "MyHTMLView", myModel );
                //where file MyHTMLView.cstml is stored in Views/Email/MyHTMLView.cshtml. Email is a fake controller name.
            }
        }
        catch (Exception ex)
        {
            //do your exception handling here
        }
    }
}

这是你如何从另一个控制器调用它

var modal = getModal(params);
return FakeController.RenderViewToString(controllerName, viewName, areaName, modal, this.Request.RequestContext);

使用requestcontext我们可以轻松地在fakecontroller中传递当前会话并呈现razor字符串。

答案 2 :(得分:2)

我迫切需要在JSON对象中将6个部分视图作为字符串返回。我决定将受保护的方法添加到源自Controller的ControllerBase类,而不是创建静态方法并传递所有不需要的参数,并将其用作所有控制器的基类。

这是一个功能齐全的ControllerBase类,它提供此功能,其工作方式与Controller类中的PartialView()和View()方法非常相似。它包括@Alok的补充。

public abstract class ControllerBase : Controller
{
    #region PartialViewToString

    protected string PartialViewToString(string partialViewName, object model = null)
    {
        ControllerContext controllerContext = new ControllerContext(Request.RequestContext, this);

        return ViewToString(
            controllerContext,
            ViewEngines.Engines.FindPartialView(controllerContext, partialViewName) ?? throw new FileNotFoundException("Partial view cannot be found."),
            model
        );
    }

    #endregion

    #region ViewToString

    protected string ViewToString(string viewName, object model = null)
    {
        ControllerContext controllerContext = new ControllerContext(Request.RequestContext, this);

        return ViewToString(
            controllerContext,
            ViewEngines.Engines.FindView(controllerContext, viewName, null) ?? throw new FileNotFoundException("View cannot be found."),
            model
        );
    }

    protected string ViewToString(string viewName, string controllerName, string areaName, object model = null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", controllerName);

        if (areaName != null)
        {
            routeData.Values.Add("Area", areaName);
            routeData.DataTokens["area"] = areaName;
        }

        ControllerContext controllerContext = new ControllerContext(HttpContext, routeData, this);

        return ViewToString(
            controllerContext,
            ViewEngines.Engines.FindView(controllerContext, viewName, null) ?? throw new FileNotFoundException("View cannot be found."),
            model
        );
    }

    #endregion

    #region Private Methods

    private string ViewToString(ControllerContext controllerContext, ViewEngineResult viewEngineResult, object model)
    {
        using (StringWriter writer = new StringWriter())
        {
            ViewContext viewContext = new ViewContext(
                ControllerContext,
                viewEngineResult.View,
                new ViewDataDictionary(model),
                new TempDataDictionary(),
                writer
            );

            viewEngineResult.View.Render(viewContext, writer);

            return writer.ToString();
        }
    }

    #endregion
}

答案 3 :(得分:0)

@ wh1sp3r答案有效,但对于部分视图,我必须进行以下较小更改:

 string html = FakeController.RenderViewToString("**Controllername**", "~/views/**Controllername**/_AsdfPartialPage.cshtml", fem);


public static string RenderViewToString(string controllerName, string viewName, object viewData)
    {
        using (var writer = new StringWriter())
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://localhost", null), new HttpResponse(null))), routeData, new FakeController());
            var razorViewEngine = new RazorViewEngine();
            //var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

            var razorViewResult = razorViewEngine.FindPartialView(fakeControllerContext, viewName,  false);

            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
            razorViewResult.View.Render(viewContext, writer);
            return writer.ToString();

        }
    }

答案 4 :(得分:0)

要将PartialView呈现为字符串,请使用以下代码:

class FakeController: ControllerBase {
    protected override void ExecuteCore() { }
    public static string RenderViewToString(string controllerName, string viewName, object model) {
        using(var writer = new StringWriter()) {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://localhost", null), new HttpResponse(null))), routeData, new FakeController());
            var razorViewEngine = new RazorViewEngine();
            var razorViewResult = razorViewEngine.FindPartialView(fakeControllerContext, viewName, false);
            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(model), new TempDataDictionary(), writer);
            razorViewResult.View.Render(viewContext, writer);
            return writer.ToString();

        }
    }
}