C#C
C#3y ago
teauxfu

❔ Razor pages asp-validation-for="MyProperty " vs asp-validation-summary="All"

I am working on a simple registration form using a Razor page, and having trouble getting a message manually added with ModelState.AddModelError to show up.

My form has a <span asp-validation-for="Foo"></span> for each input, as well as a <div asp-validation-summary="All"></div>.
I've used attributes on my model to supply some validation rules. Those are working fine -- errors from failing the attributes will make an error message show up in both the span and the div
The problem is that, after doing some custom logic (checking for existing user email) and manually adding an error to the ModelState, the custom error message will only show up in the div, not in the <span>.

If I change the div to <div asp-validation-summary="ModelOnly"></div>, then the manually added error stops showing there as well. This makes me suspect I'm adding the error wrong, but there's not a lot of room for variation. Any ideas on what I'm doing wrong? Thanks for taking the time to read/answer.

 public class InputModel
{

    [Required(AllowEmptyStrings = false)]
    public string FirstName { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}


public async Task<IActionResult> OnPostAsync()
{
    // only try adding user if attribute validation passes
    if (ModelState.IsValid)
    {
        // ... try adding new user to db
        if (result.Succeeded)
        {
          // ... other work
        }
        else
        {
            // ... check if failed due to existing user
            if (duplicateAccountError)
                ModelState.AddModelError(nameof(InputModel.Email), "Email already exists.");
        }
    }

    return Page();
}


YouTube video proof of concept ? https://youtu.be/PtzH6vu91e8?t=666
image.png
YouTubeSameer Saini
👉ASP.NET Razor Pages Full Course:
https://www.udemy.com/course/aspnet-core-razor-pages-web-application-development/?couponCode=MAY2023

In this video, we will see how we can create form and model validations in an ASP.NET Core 6 Razor Pages application.
We will submit a form in a razor pages application and then validate the values of the form a...
Was this page helpful?