本文介绍了将视图渲染为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Am试图将视图呈现为要用作电子邮件模板的字符串.我目前正在尝试实现此示例: https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String

Am trying to render a view as a string to be used as an email template. Am currently trying to implement this example:https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String

但是这段代码有困难:

public ViewRenderer(ControllerContext controllerContext = null)
{
    // Create a known controller from HttpContext if no context is passed
    if (controllerContext == null)
    {
        if (HttpContext.Current != null)
            controllerContext = CreateController<ErrorController>().ControllerContext;
        else
            throw new InvalidOperationException(
                "ViewRenderer must run in the context of an ASP.NET " +
                "Application and requires HttpContext.Current to be present.");
    }
    Context = controllerContext;
}

Visual Studio给我以下错误:

Visual Studio is giving me the following error:

可能遗漏了一些明显的东西,但看不到它是什么.有什么想法吗?

Am probably missing something obvious but can't see what it is. Any ideas?

推荐答案

如果您需要将视图呈现为字符串,这是我编写的控制器的扩展方法.

If you need to Render your view as a string, here is an extension method for the controller I wrote.

注意:我将尝试找到用于帮助我的确切链接,并在找到答案时更新我的​​答案.

此处是描述此方法的另一个链接.

Here is another link, describing this method.

这应该可以解决问题:

public static string RenderViewToString(this Controller controller, string viewName, object model)
    {
        var context = controller.ControllerContext;
        if (string.IsNullOrEmpty(viewName))
            viewName = context.RouteData.GetRequiredString("action");

        var viewData = new ViewDataDictionary(model);

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
            var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }

如果要从控制器调用它,只需执行以下操作:

If you want to call this from a controller, you simply do the following:

var strView = this.RenderViewToString("YourViewName", yourModel);

这篇关于将视图渲染为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 01:23