简体   繁体   中英

Blazor: Define namespace in Razor File

Question: Is there a way to define a namespace in a.razor file in Blazor.

Problem Explanation: Razor files in Blazor do not have a namespace defined (only the code behind class has one and it should match the.razor file location in the project). This resulted in a problem on GitHub and it restrict me from offering a Razor Component Library with few namespaces.

Github problem: This stems from a Microsoft philosophy I do not subscribe to: filenames are not case sensitive. I had a folder, lets say it was named 'FooBar'. In my project I renamed it 'Foobar'. Either Windows did not rename it properly, or when checking in in Github it was not seen as a change. As a result, my code behind namespace 'Foobar' no longer matched the namespace of my /razor file 'FooBar', resulting in a build error on Github (it worked fine on my pc). If I had been able to specify the namespace in the.razor file this would not have happened.

Component library problem: I am making a component library I want to offer on NuGet. I want to keep all my components in separate folders (let's say for Single responsibility sake). When I now want to include this component library, the _imports file will have a @include for each folder that is part of the library, again because I am unable to separate working with folders from the namespace the components are in. I would like to say @include Foobar rather than @include Foobar.Checkbox , @include Foobar.Radiobutton etc, etc.

So is there any solution to this?

Ok I did not find this googling (It might be somewhere though) but I tried the following:

In the code behind rename the namespace Foobar.Checkbox to Foobar in the razor file add @namespace Foobar

Yes it is that simple facepalm

By example. Your Blazor component name is Box, in folder Boxes.

You namespace should be Boxs - Right?

Do this: Add a class in Boxs folder with name Box.razor.cs. This class is the C# code of Box, then add to this class:

using Microsoft.AspNetCore.Components;

namespace Boxes;

public partial class Box: ComponentBase
{
// @code ...
}

To make easy, add the Boxs namespace to _imports.razor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM