Using razor components (Blazor) in an asp.net core web app using razor pages

Nigel 271 Reputation points
2022-11-23T07:46:31.02+00:00

Hi, I am developing a web app using http://asp.net core razor pages. I want to use razor components (blazor) to input string data and act on it (using C#). However, although although the text input boxes show, all the data binding to objects stops working.

I am using:

<component type="typeof(Components.Name1)" render-mode="Static" />  

to embed the razor component into my razor page.

The blazor component is simply:

<h3>Name1</h3>  
  
<p>  
    <label>  
        Please enter your name:  
        <input @bind="name" ;  
    </label>  
</p>  
  
<button class="btn btn-primary"   
@onclick  
="getName">Enter</button>  
  
<p role="status">Hello   
@Name  
 I hope you are having a good day</p>  
  
@code  
 {  
    private string name { get; set; }  
    private string Name;  
  
    private void getName()  
    {  
        Name = name;  
    }  
}  

The full repo can be found at ASP.NET.CORE.WEB.DEMO

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,385 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-11-24T06:36:50.393+00:00

    Hi @Nigel ,

    However, although although the text input boxes show, all the data binding to objects stops working.

    I checked your code, not only the data binding but also the button click event also not work, right?

    To solve this issue, you need to change these parts:

    1. Change the Render Mode from Static to ServerPrerendered: because when using the static mode, it will render the component into static HTML. <component type="typeof(Components.Name1)" render-mode="ServerPrerendered" />
    2. In the Program.cs file, add the MapBlazorHub middleware and AddServerSideBlazor service:
      builder.Services.AddServerSideBlazor();  
      
      app.MapBlazorHub();  
      
    3. In the _Layout.cshtml page, add the _framework/blazor.server.js script reference: 263793-image.png
    4. In the Name1 component, add the Microsoft.AspNetCore.Components and Microsoft.AspNetCore.Components.Web reference: 263811-image.png

    Then the result as below:

    263765-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful