Add control dynamically to razor page using C#.NET Core 3.1

Viewed 31

I am building a web application using the ASP.NET C# Core 3.1 MVC and Razor pages.

I am new to Razor pages.

I want to add a button dynamically to the razor page through c#.net core backend code.

I have following sample ASP.NET code syntax that adds the html control present in the string "strForm", to the asp page.

Page.Controls.Add(new LiteralControl(strForm));

What is the equivalent of the above code in C#.NET Core 3.1?

1 Answers

In ASP.NET Core, you cannot target the html and add html to it like ASP.NET by default, but you can use @Html.Raw(htmlstring) to display the string to html. And use ViewData to dynamically control the html string.

A whole working demo you could follow

Razor Page:

@page
@model IndexModel

@if(ViewData["Html"] != null)
{
    @Html.Raw(ViewData["Html"])
}

PageModel:

public class IndexModel: PageModel
{

    public void OnGet()
    {
        ViewData["Html"] = "<button id=\"btn\" class=\"btn btn-primary\">Click</button>";
    }
}
Related