Search code examples
blazorblazor-client-side

Define a Blazor Page using .razor.cs file only; no .razor file


I was hoping the "Test.razor.cs" file below (with no corresponding "Test.razor" file hence no "partial" ) would actually work as a Page for example. But I get the "Sorry, there's nothing at this address." error when going to ".../Test"

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using NorthWind.UI.Shared;

namespace NorthWind.UI.Pages
{
    public class Test : ComponentBase
    {

        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            builder.OpenComponent(0, typeof(SurveyPrompt));
            builder.AddAttribute(1, "Title", $"Some Test");
            builder.CloseComponent();

            base.BuildRenderTree(builder);
        }
    }
}

Is there a way to add it to the pages that Blazor can evaluate too (other than adding a front end .razor file )?


Solution

  • The Answer is to add the Microsoft.AspNetCore.Components.RouteAttribute to the class

        [Route("/Test")]
        public partial class Test : ComponentBase
        {
    
            protected override void BuildRenderTree(RenderTreeBuilder builder)
            {
                builder.OpenComponent(0, typeof(SurveyPrompt));
                builder.AddAttribute(1, "Title", $"Some Test");
                builder.CloseComponent();
    
                base.BuildRenderTree(builder);
            }
        }