You're looking for @Html.Raw(value)
, which will prevent Razor from escaping it.
Convert text to html with streamreader
-
05-06-2023 - |
Question
I have a helper that passes the path and key to look at a cshtml file.
But what it returns is the HTML but as text, so the browser is not able to compile it.
How can I write this helper to take the string and get it to a true HTML string, I've tried encoding and decoding and either I see the code, or the entities, but the browser still isn't converting it.
So what I need is @data to be HTML that get's interpreted as HTML. Is there another method of reading the file that could help?
Example code:
@helper readPattern(string filepath, string patternSection = null)
{
TextReader tr = new StreamReader(filepath);
string SplitBy = "<!-- START: " + patternSection + " -->";
string EndBy = "<!-- END: " + patternSection + " -->";
string fullLog = tr.ReadToEnd();
tr.Close();
int start = fullLog.IndexOf(SplitBy);
int end = fullLog.IndexOf(EndBy);
int startLen = SplitBy.Length;
int endLen = EndBy.Length;
string data = fullLog.Substring(start + startLen, end - (start + endLen) - 2);
@* Return Data *@
<div data-meta="@patternSection">@data</div>
}
Correct Code: - Static Helper
@helper readPattern(string filepath, string patternSection = null)
{
TextReader tr = new StreamReader(filepath);
string SplitBy = "<!-- START: " + patternSection + " -->";
string EndBy = "<!-- END: " + patternSection + " -->";
string fullLog = tr.ReadToEnd();
tr.Close();
int start = fullLog.IndexOf(SplitBy);
int end = fullLog.IndexOf(EndBy);
int startLen = SplitBy.Length;
int endLen = EndBy.Length;
string data = fullLog.Substring(start + startLen, end - (start + endLen) - 2);
@* Return Data *@
<div data-meta="@patternSection">@(new HtmlString(data))</div>
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow