本文介绍了有没有使用Razor生成静态HTML页面的例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我尝试了T4作为RAZOR生成静态HTML页面,基本上使用包含部分子页面。以及寻找替代方法:请参阅和

  2. 这个表示可以 - 但没有具体的例子

  3. 我已经安装了,因为我认为这是要走的路,但我没有得到如何生成静态HTML。

Best将是一个完整的扩展,其行为与T4概念类似,但允许我使用RAZOR语法和 HTML格式(格式问题是基本的我不使用T4)。

解决方案

如果您尝试使用Razor视图并编译并生成HTML,那么你可以使用这样的东西。

  public static string RenderViewToString(string viewPath,object model,ControllerContext context)
{
var viewEngineResult = ViewEngines.Engines.FindView(context,viewPath,null);
var view = viewEngineResult.View;


context.Controller.ViewData.Model = model;

字符串结果= String.Empty;
using(var sw = new StringWriter())
{

var ctx = new ViewContext(context,view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx,sw);

result = sw.ToString();
}

返回结果;
}

或者在ControllerContext之外


I want to generate a static HTML page by RAZOR, basically by using includes of partial sub pages.

  1. I have tried T4 as well and do look for an alternative: see here and here
  2. This answer says it is possible - but no concrete example
  3. I have installed Razor generator because I thought this is the way to go, but I do not get how to generate static HTML with this.

Best would be a complete extension which behaves like the T4 concept, but allows me to use the RAZOR syntax and HTML formatting (the formatting issue is basically the reasons why I am not using T4).

解决方案

If you are trying to take a Razor view and compile it and generate the HTML then you can use something like this.

public static string RenderViewToString(string viewPath, object model, ControllerContext context)
{
    var viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
    var view = viewEngineResult.View;


    context.Controller.ViewData.Model = model;

    string result = String.Empty;
    using (var sw = new StringWriter())
    {

        var ctx = new ViewContext(context, view,
                                  context.Controller.ViewData,
                                  context.Controller.TempData,
                                  sw);
        view.Render(ctx, sw);

        result = sw.ToString();
    }

    return result;
}

Or outside of ControllerContext http://razorengine.codeplex.com/

这篇关于有没有使用Razor生成静态HTML页面的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:15