当我的 modelstate 无效时,如何将 CSS 类添加到输入元素?

Kje*_*ous 7 css .net-core razor-pages

我是 .NET Core 2.0 Razor 页面的新手,我发现很难以干净的方式解决我的问题。

我创建了一个简单的登录表单,用户必须在其中输入其电子邮件和密码。我使用的模型具有电子邮件和密码的属性以及相应的数据注释。

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; }
}
Run Code Online (Sandbox Code Playgroud)

我的页面模型如下所示:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我的 ModelState 无效时,我想显示一条错误消息。这与以下代码配合得很好:

<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>
Run Code Online (Sandbox Code Playgroud)

.is-invalid此外,当我的 Modelstate 对于该特定属性无效时,我想在我的输入元素上添加 CSS 类。这会产生一个红边输入元素(引导程序 4)。我用下面的代码让它工作:

<input type="text" class="form-control @(ModelState["Command.Email"]?.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid ? "is-invalid": string.Empty)" asp-for="Command.Email">
Run Code Online (Sandbox Code Playgroud)

老实说,我不喜欢这个解决方案。

当对类实例名称或属性执行重命名时,硬编码的“Command.Email”会破坏代码。在尝试了几件事之后,我没有找到一个好的、干净的方法来解决这个问题。

Ful*_*ime -1

看看用于前端验证的不显眼的 jQuery。您将能够使用 jQuery 来查看表单是否有效,然后根据需要应用 CSS 类。