Home > Blockchain >  ASP.NET Core 7 MVC shows the Razor component twice
ASP.NET Core 7 MVC shows the Razor component twice

Time:12-28

I used my Razor component in my view and it ended up showing the same component twice.

I don't know why it happens, but once in 2 times, it shows the component normally. I use .NET 7.

enter image description here

Create.razor (used component)

@using CarStock.Data
@using Microsoft.AspNetCore.Components.Forms
@inject NavigationManager NavigationManager
@inject IPostService postS

<EditForm Model="@Post" OnValidSubmit="@CreatePost">
    <DataAnnotationsValidator />

    <div >
        <label for="Title">Title</label>
        <InputText id="Title" @bind-Value="Post.Title"  />
    </div>
    <div >
        <label for="Content">Content</label>
        <InputTextArea id="Content" @bind-Value="Post.Content"  />
    </div>
    <button onclick="@CreatePost()" >Create</button>
</EditForm>

@code {
    Post Post = new Post();

    async Task CreatePost()
    {
        // Call service to create post
        await postS.CreatePost(Post);

        NavigationManager.NavigateTo("Blog", true);
        await Task.CompletedTask;
    }
}

Create.cshtml (view page)

@using CarStock.Components.Blog;
@model CarStock.Data.Post

@{
    ViewBag.Title = "Create";
}

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

CodePudding user response:

Have you seen https://learn.microsoft.com/en-us/aspnet/core/blazor/components/prerendering-and-integration?view=aspnetcore-7.0&pivots=server#render-components-from-a-page-or-view?

Try using

<component type="typeof(Create)" render-mode="ServerPrerendered"/>

And on the other hand if you only are using the Razor component and integrating Blazor functionality for the create form post, consider using a View Component instead.

CodePudding user response:

Thanks @Rena for a hint. It was dublicating because I had this line twice in my layout

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

Funny bug

  • Related