How do I display server side validation errors in Blazor (webassembly/wasm) using the ValidationSummary component?

912 Views Asked by At

For Blazor client side (webassembly/wasm), are there any good examples of how to display a server side error that occurs during submitting data to the server?

I would like to just display them in the ValidationSummary component. What might the best approach for that? Is there a sample of how to display the server side error, just like a client side error?

I am already trapping any errors and inspecting the ProblemDetails (or ValidationProblemsDetails). But I have no idea how to "display" these issues in the ValidationSummary.

2

There are 2 best solutions below

3
MrC aka Shaun Curtis On

You only get what the Server side API returns. If it's your API get it to return an object containing the necessary information.

I use something like this:

    public class DbTaskResult
    {
        public string Message { get; set; } = "New Object Message";
        public MessageType Type { get; set; } = MessageType.None;
        public bool IsOK { get; set; } = true;
        public int NewID { get; set; } = 0;

        public static DbTaskResult OK(int id = 0)
            => new DbTaskResult() { IsOK = true, Type = MessageType.Success, NewID = id };

        public static DbTaskResult NotOK(int id = 0)
            => new DbTaskResult() { IsOK = false, Type = MessageType.Danger};
    }

As for displaying in Validation Summary, ??? That's geared for validation of individual fields. The above object is coded to return information that can be quickly transformed into an Alert or Toast.

I've shown as example alert below - hides/shows and changes colour based on the alert type - slightly custom bootstrap alert.

enter image description here

1
Tim Bassett On

There's a great article on how to do something like this: https://blazor-university.com/forms/writing-custom-validation/