Hosting the Razor View Engine using a view model

2019-07-23 05:58发布

问题:

I'd like to use the Razor View Engine outside of ASP.NET MVC to generate HTML for emails, I like the syntax and it seems unnecessary to use another templating engine when I already have Razor in my project.

So I looked around and found this guide on how to do it.. http://blog.andrewnurse.net/2010/11/16/HostingRazorOutsideOfASPNetRevisedForMVC3RC.aspx

Unfortunately I can't find any way of specifying a view model, which is sad because I would really, really like to have strongly typed views even for my emails.

So is there any way of parsing Razor templates outside of ASP.NET MVC with strongly typed view models or is it so much trouble it's not worth the hassle?

回答1:

Using the @model tag is actually a shortcut for the @inherits tag.

You specify the class, your generated class will inherit from from the class specified with @inherits.

So if you specify @inherits MyTemplate<MyModel>

MyTemplate should look like:

class MyTemplate<T> {
    public T Model { get; set; }

    public abstract void Execute();
    public virtual void Write(object value) {
        WriteLiteral(value);
    }

    public virtual void WriteLiteral(object value) {
        // Actual writing goes here
    }

}

The result from the razor parsing, you need to compile, and create an instance from.

After you created the instance you can set the Model property, and call Execute to generate the result, how and what you generate is up to you.



回答2:

With the last stable RazorEngine it is enough to specify

@inherits RazorEngine.Templating.TemplateBase<MyModel>

unless you need some more functionality