Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML in a variable MVC4 Razor

I am rather new to .net and Razor, but I am building a view that will have HTML rendered on the page, and then displayed in code block, instead of writing it twice I wanted to assign the HTML to a variable and then output it encoded and decoded in different spots.

Ideally I want to be able to write normal HTML with double quotes for attributes without having to escape them.

In the end I want the person using this template to be able to be able to just copy HTML into the variable and let the rest be automatic, I would just return a partial view which does encoding, but I have @section renders that I do not know how to put into a controller, or how to load more than 1 view in a controller.

Here's example code:

@section componentStyles {
    @Styles.Render("~/Includes/CSS/components/cui-" + ViewData["component"] + ".css")
}

@section componentScripts {
    @Scripts.Render("~/Includes/JS/components/cui-" + ViewData["component"] + ".js")
}

@*
    Begin Markup for Component, Add it to the string variable
*@

@{

    String markup = "<h1 class=\"cui-class\">Component Markup</h1>";

}

@Html.Raw(HttpUtility.HtmlDecode(@markup))

@if (ViewData["details"] is bool && (bool)ViewData["details"] == true)
{
    <pre class="line-numbers">
        <code class="language-markup">@Html.Raw(HttpUtility.HtmlEncode(@markup))</code>
    </pre>
}
like image 622
thematt Avatar asked Sep 18 '25 15:09

thematt


1 Answers

You can use inline helpers to wrap a snippet of Razor code:

@helper MyPieceOfCode(string message) 
{
    <p id="message">@message</p> // this is actually fully covered by intellisense
}

@MyPieceOfCode("hello world!") // equals to <p id="message">hello world!</p>
like image 143
tocqueville Avatar answered Sep 20 '25 06:09

tocqueville