Home > OS >  Razor Component is not rendered
Razor Component is not rendered

Time:09-28

I am fairly new to Blazor and tried to use a Razor Component in my Index.cshtml but it wouldn't work. Maybe you can give me a hint where the mistake lies.

The Component (FileUploadComponent.razor) is located in the same folder: enter image description here

FileUploadComponent:

@inherits ComponentBase

<h3>FileUploadComponent</h3>
Test

Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    <FileUploadComponent />
</div>

CodePudding user response:

You can use Blazor components in Razor pages, but it takes a few more steps.

In your .cshtml page(s)

<component type="typeof(MyComponent)" render-mode="Server" />

@section Scripts {
    <script src="_framework/blazor.server.js"></script>
}

and in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();  // add this
    }

    ....


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapBlazorHub();   // and this
        });

CodePudding user response:

The following steps describe how you can instantiate the FileUploadComponent component in your Index page:

Index.cshtml

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    
<component type="typeof(FileUploadComponent)" 
           render-Mode="ServerPrerendered" 
           param-Name="@value" />
</div>

Note that param-Name="@value" is added here to demonstrate how you can pass a parameter to your Razor component... You can remove it of course.

Add the following script tag at the end of your _Layout.cshtml file like this:

<script src="_framework/blazor.server.js"></script>
</body>

And finally, add the following settings into your Startup class:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddServerSideBlazor();
        }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment 
                                                                env)
 {
      // Code removed for brevity's sake
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapBlazorHub();
           // Enable this if you're using the _Host.cshtml file 
           // endpoints.MapFallbackToPage("/_Host");
        });
 }

Note: You shouldn't use this: @inherits ComponentBase

  • Related