Blazor namespace and @namespace

Albert 1 Reputation point
2021-01-30T21:30:03.727+00:00

I have a Blazor component where markup and code are separated ( AppNav.razor and AppNav.razor.cs).

Do I have to put namespace in both files or .razor.cs is sufficient?

I have this question because Visual studio 2019 (16.8.3) Enterprise is inconsistent. Sometimes it allows me to use components without specifying @namespace in razor file ( I assume it is enough to have it in .razor.cs). But after restarting Visual studio it gives me error about missing component and it only can be fixed if I put @namespace in *.razor file also.

So what is the correct way ?

AppNav.razor

<div class="appnav">
    <div class="tree navigation">
    </div>
</div>
@namespace MyApp.Shared.App @*duplicating here*@
@code {

}

AppNav.razor.cs

using Microsoft.AspNetCore.Components;


namespace MyApp.Shared.App
{
    public partial class AppNav
    {
        [Inject]
        private NavigationManager _navigation { get; set; }

        public void NavigateTo(string route)
        {
             _navigation.NavigateTo(route);
        }
    }
}

_Imports.razor

...
@using MyApp.State
@using MyApp.Shared.App
...
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,427 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,408 questions
{count} votes