Generate a simple message from controller (blazor page not for razor view)

perfect code 271 Reputation points
2023-01-29T12:11:47.5833333+00:00

In a Blazor server application, I have implemented user authentication via cookie. In the Blazor page (not razor view) I have created a form with email and password entries as well as a button for sending the data. The method is Post and is run on the server via a controller. In the controller I then check the form entries and verify the user by checking his name and password in the database.

So far, everything works as expected.

My problem, however, is the message in the event of an incorrect login (e.g. password is incorrect). I have been looking for a solution and the only solution is a communication between controller and Razor-View (.cshtml) via ViewBag. This is not possible in my case because I use a Blazor page and the login window is part of the Blazor navigation (in other words, I would have to do it like in the Microsoft login template by redirecting login to a separate Razor view .cshtml and I don't want that).

I only have one idea at the moment, but I don't like it. The approach would be to create a static class and use it as a link between the controller and the blazor page. Then I can use the information I set in the controller (e.g. login failed) to generate a corresponding message in the Blazor page. Of course, I would have to generate a GUID in addition to the email and password so that I can distinguish the logged-in user from all the other app-users.

So the question is, is there another way to generate a message (also e.g. simple JS alert) based on controller information in the Blazor page?

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,134 questions
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,375 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,243 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,197 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,181 Reputation points
    2023-01-29T15:15:12.7533333+00:00

    Your current solution returns a redirect that tells the browser to load the Blazor application. Add parameters to the URL.

    Blazor read a parameter

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    
    <p>Message: @Message</p>
    
    @code {
        [Parameter]
        [SupplyParameterFromQuery]
        public string? Message { get; set; }
    
    }
    

    Redirect with parameter

    return Redirect("/?message=Hello World")
    
    0 comments No comments

0 additional answers

Sort by: Most helpful