RazorEngine: cannot use Html.Raw
Asked Answered
A

4

28

using RazorEngine outside asp.net I'm experiencing this error when I try to write raw html by using @Html.Raw("html string here"):

Unable to compile template. The name 'Html' does not exist in the current context

Can you help me?

Thanks!

Azotobacter answered 12/5, 2014 at 7:46 Comment(2)
Why is this downvoted? This question helped me.Sociometry
Probably because people assume its a standard razor question not the engine.Micaelamicah
A
31

The solution has been found here: https://github.com/Antaris/RazorEngine/issues/34

It's enough to use @(new RawString("html string here")) or @Raw("html string here") instead of @Html.Raw("html string here").

I hope this helps! Bye

Azotobacter answered 12/5, 2014 at 7:46 Comment(2)
Neither of these work with dotnet 5 anymore.Marshall
It works (with aspnet 4.x) but the the cshtml still cry a "CS0103 The name 'Raw' does not exist in the current context" fake error.Vargo
D
6

I implemented my own Raw whose result implements both IHtmlString and IEncodedString... and it worked! :)

In my csthml:
@MyRazorParser.Raw("<b>Testing</b>")

This works both when MVC uses it and when the RazorEngine parser uses it.

public class MyRawResult : RazorEngine.Text.IEncodedString, System.Web.IHtmlString
{
    public string Value;
    public MyRawResult(string value) { Value = value; }
    public string ToEncodedString()
    {
        return Value;
    }

    public string ToHtmlString()
    {
        return Value;
    }

    public override string ToString()
    {
        return Value;
    }
}

public static class MyRazorParser
{
    public static object Raw(string str)
    {
        return new MyRawResult(str);
    }
}
Daudet answered 21/10, 2015 at 20:24 Comment(0)
T
2

In my case my _ViewImports.cshtml file was missing a reference to:

@using Microsoft.AspNetCore.Mvc;

Once I added this ff8mania's answer worked for me.

Trumpet answered 18/10, 2021 at 16:44 Comment(0)
P
0

I had a similar problem with RazorLight not being able to handle @Html.Raw calls in partial views. I just made a Utility class with a Raw method and used that instead.

public static IHtmlContent Raw(string? str)
    {
        return new HtmlString(str);
    }

This works because my namespace is already being injected into the RazorLight engine.

private RazorLightEngine engine = new RazorLightEngineBuilder()
        .UseFileSystemProject(Directory.GetCurrentDirectory().ToString())
        .AddDefaultNamespaces("MyCoolProject.Models")
        .UseMemoryCachingProvider()
        .Build();

Then replace @Html.Raw(Model.HtmlString) with @Utility.Raw(Model.HtmlString) and you're ducky.

Plantation answered 24/2, 2023 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.