1

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?

2
  • How dynamic exactly? Do you just need @if(Model.something){ <button></button> }? In other words, try to keep your model and view separate. Raw html in your model should be avoided. But all rules are made to be broken... Commented Sep 23, 2022 at 6:31
  • Hi @devman, any update here? Commented Oct 6, 2022 at 1:06

2 Answers 2

0

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>";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

MVC doesn't use a control tree; you just need to return the raw HTML to the user: C#

We have to do the following - Replace

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

By

return Content(strForm, System.Net.Mime.MediaTypeNames.Text.Html);

Please refer url for reference -

"https://www.codeproject.com/Questions/1230430/Unable-to-redirect-user-to-payment-page-of-the-pay"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.