Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define function that returns html in asp.net core

Basically I need something like old asp.net

@helper MakeNote(string content) {
    <p><strong>Note</strong>&nbsp;&nbsp; @content    </p>
}

or JSX

MakeNote(note) {
   return (<div>Note {note}</div>);
}

A partial view is not an option. I am happy with either a function returning an IHtmlString, or a function writing to the underlying writer.

It also needs to support Razor Syntax (not just string concatenation) inside the function.

like image 362
Shadow Avatar asked Aug 30 '18 19:08

Shadow


People also ask

Can we return HTML from Web API?

A typical web API returns JSON or XML responses. However, rare cases exist where we need to return responses in other formats. In this article, we are going to learn how to return HTML from ASP.NET Core Web API. We will also state some use cases for this type of API.

What is Cshtml vs HTML?

Cshtml is basically razor view extension and any view renders in html finally. You need to use Razor in your application as it supports server side code but raw html does not.


1 Answers

Since ASP.NET Core 3.0, we can declare Local Functions containing markup to serve as templating methods, inside Razor Code Blocks:

@{
    void RenderName(string name)
    {
        <p>Name: <strong>@name</strong></p>
    }

    RenderName("Mahatma Gandhi");
    RenderName("Martin Luther King, Jr.");
}

Which renders the following HTML Code:

<p>Name: <strong>Mahatma Gandhi</strong></p>
<p>Name: <strong>Martin Luther King, Jr.</strong></p>

Documentation: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.0#razor-code-blocks


(just for sake of completion) In ASP.NET Core 2.0 we can use Templated Razor delegates, which combined with the <text></text> razor tag (Explicit Delimited Transition), allow us to make something similar to an old day's ASP.NET MVC @helper tag:

@{
    Func<string, object> RenderName = @<text>
        <p>
            Name: <strong>@item</strong>
        </p>;
    </text>;
}

<div>
    @RenderName("Victor")
</div>

Which renders the following HTML Code:

<div>
    <p>
        Name: <strong>Victor</strong>
    </p>
</div>

Documentation: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#templated-razor-delegates
Documentation <text></text>: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#razor-code-blocks

like image 150
Vitox Avatar answered Oct 07 '22 04:10

Vitox