C# 如何在 ASP.NET MVC 3 中将 Razor 视图呈现为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9243433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:30:58  来源:igfitidea点击:

How to render a Razor View to a string in ASP.NET MVC 3?

c#asp.net-mvcasp.net-mvc-3razor

提问by bevacqua

I've been searching the site a lot, but all I could find were examples on how to render partial controls .ascx, or depended on a controller context.

我一直在该网站上搜索了很多,但我能找到的只是关于如何呈现部分控件.ascx或依赖于控制器上下文的示例。

I want a method that enables me to provide just the relative path to the view, and a model, and render that view with that model into a string:

我想要一种方法,使我能够仅提供视图的相对路径和模型,并将该视图与该模型渲染为字符串:

string result = Utility.RenderViewToString("~/Views/My/Profile.cshtml", model);

All the examples I could find were either for older versions of MVC, or simply didn't do what I need to do here.

我能找到的所有例子要么是针对旧版本的 MVC,要么就是没有做我需要在这里做的事情。

采纳答案by Marc

You can achieve that with the razorengine.

您可以使用razorengine实现这一点

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

And it does not rely on the controller context - but because of that you are not able to use the Html helpers (which rely on the http context). But it is perfect to use razor as a template engine for strings.

并且它不依赖于控制器上下文 - 但因此您无法使用 Html 助手(依赖于 http 上下文)。但是使用 razor 作为字符串的模板引擎是完美的。

回答by Ravi Gadag

You can check this link.

您可以查看此链接。

extracted content From Render Razor view to String. .

提取内容从 Render Razor 视图到 String。.

public static string RenderRazorViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        return sw.GetStringBuilder().ToString();
    }
}

回答by Oleksandr Fentsyk

I had created solution for me. It's Extension that render view into string.

我已经为我创建了解决方案。它是将视图呈现为字符串的扩展。

public static class RenderPartialToStringExtensions
{
    /// <summary>
    /// render PartialView and return string
    /// </summary>
    /// <param name="context"></param>
    /// <param name="partialViewName"></param>
    /// <param name="model"></param>
    /// <returns></returns>
    public static string RenderPartialToString(this ControllerContext context, string partialViewName, object model)
    {
        return RenderPartialToStringMethod(context, partialViewName, model);
    }

    /// <summary>
    /// render PartialView and return string
    /// </summary>
    /// <param name="context"></param>
    /// <param name="partialViewName"></param>
    /// <param name="viewData"></param>
    /// <param name="tempData"></param>
    /// <returns></returns>
    public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
    {
        return RenderPartialToStringMethod(context, partialViewName, viewData, tempData);
    }

    public static string RenderPartialToStringMethod(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
    {
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

        if (result.View != null)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter output = new HtmlTextWriter(sw))
                {
                    ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                    result.View.Render(viewContext, output);
                }
            }

            return sb.ToString();
        }
        return String.Empty;
    }

    public static string RenderPartialToStringMethod(ControllerContext context, string partialViewName, object model)
    {
        ViewDataDictionary viewData = new ViewDataDictionary(model);
        TempDataDictionary tempData = new TempDataDictionary();
        return RenderPartialToStringMethod(context, partialViewName, viewData, tempData);
    }
}

And than we can render view in Action

然后我们可以在 Action 中渲染视图

[HttpPost]
public ActionResult GetTreeUnit(string id)
{
    int _id = id.ExtractID();
    string render = ControllerContext.RenderPartialToString("SomeView");
    return Json(new { data = render });
}

回答by Rohit Arora

Though Marc's is answer is correct and works for previous versions. But that is now obselete and needs to be replaced.

尽管 Marc 的答案是正确的,并且适用于以前的版本。但是现在已经过时了,需要更换。

Here is the new code that worked for me and you can find more useful information on Github : Razor Engine

这是对我有用的新代码,您可以在 Github 上找到更多有用的信息:Razor Engine

string template = "Hello @Model.Name! Welcome to Razor!";
string Result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });