Search code examples
c#razorrazorengine

razor engine template parse without specific type


Is there a way to RunCompile() a Razor Engine template without declaring typeof(someType) ?

I want to avoid having multiple methods like these:

    public static string EvalueateLineChartModelTemplate(d3LineCharts.LineChartModel model, string cssResourceName, string tempKey)
    {
        string template = StreamEmbeddedResource(cssResourceName);
        string result = Engine.Razor.RunCompile(template, tempKey, typeof(d3LineCharts.LineChartModel), model);
        return result;
    }

    public static string EvalueateAreaChartModelTemplate(d3AreaCharts.AreaChartModel model, string cssResourceName, string tempKey)
    {
        string template = StreamEmbeddedResource(cssResourceName);
        string result = Engine.Razor.RunCompile(template, tempKey, typeof(d3AreaCharts.AreaChartModel), model);
        return result;
    }

How can I combine these two methods into a single more generic method so that I can still call it with different types? Thanks!


Solution

  • You can make a generic method like this:

    public static string EvaluateTemplate<T>(T model, string cssResourceName, string tempKey)
    {
        string template = StreamEmbeddedResource(cssResourceName);
        string result = Engine.Razor.RunCompile(template, tempKey, typeof(T), model);
        return result;
    }
    

    You can then call the generic method just like you would for your type-specific versions:

    d3LineCharts.LineChartModel lineChartModel = new d3LineCharts.LineChartModel();
    string result = EvaluateTemplate(lineChartModel, cssResourceName, tempKey);