I'm new to .NET Core 2.0 Razor pages, and I'm finding it difficult to solve my problem in a clean way.
I create a simple login form in which the user must enter it's email and password. I use a model with the properties for the email and password with the corresponding data annotations.
public class AuthorizeOrganizationCommand
{
[Required(ErrorMessage ="Please fill in your email")]
public string Email { get; set; }
[Required(ErrorMessage ="Please fill in your password")]
public string Password { get; set; }
}
My pagemodel looks like this:
public class IndexModel : PageModel
{
public IndexModel()
{
}
[BindProperty]
public AuthorizeOrganizationCommand Command { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
// Code to validate the credentials
return RedirectToPage("/Index");
}
}
When my ModelState is invalid, I want to visualize an error message. This works just fine with the following code:
<div class="form-group">
<label class="form-label" asp-for="Command.Email">Email</label>
<input type="text" class="form-control" asp-for="Command.Email">
<small class="invalid-feedback d-block">
<span asp-validation-for="Command.Email"></span>
</small>
</div>
Additionally I want to add the CSS class .is-invalid
on my input element when my Modelstate is invalid for that specific property. This results in a red-edged input element (bootstrap 4). I made it work with the following code:
<input type="text" class="form-control @(ModelState["Command.Email"]?.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid ? "is-invalid": string.Empty)" asp-for="Command.Email">
To be honest, I don't like this solution.
The hard-coded "Command.Email" breaks the code when a rename is performed on the class instance name or property. After trying several things I didn't find a good and clean way to solve this.