在ASP.NET Core中使用ValidationMessage时,可以添加或更改默认CSS类吗? [英] Can I add to or change the default CSS class when using ValidationMessage in ASP.NET Core?

查看:98
本文介绍了在ASP.NET Core中使用ValidationMessage时,可以添加或更改默认CSS类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在剃刀组件中使用 ValidationMessage 来显示验证消息,如下所示:

I am using ValidationMessage in a razor component to show validation message, like this:

<ValidationMessage For="@(() => ViewModel.CompanyNumber)" />

这将生成以下HTML代码:

This generates this HTML code:

<div class="validation-message">The company number field is required.</div>

是否可以更改CSS类?我想使用除 validation-message 之外的其他内容.控制器将忽略添加 class ="myclass" .我还尝试了 @attributes ,但没有成功.

Is it possible to change the CSS-class? I want to use something else than validation-message. Adding class="myclass" is ignored by the controller. I've also tried with @attributes without success.

推荐答案

他们使用.NET5添加了功能,可以在实际的输入字段(

With .NET5 they added functionality to customize the validation classes on the actual input-fields (which issue 8695 was about) by way of setting a FieldCssClassProvider to the edit context. But there still seems to be no way of customizing the classes of the ValidationSummary or ValidationMessage components

直接从.NET 5文档

var editContext = new EditContext(model);
editContext.SetFieldCssClassProvider(new MyFieldClassProvider());

...

private class MyFieldClassProvider : FieldCssClassProvider
{
    public override string GetFieldCssClass(EditContext editContext, 
        in FieldIdentifier fieldIdentifier)
    {
        var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();

        return isValid ? "good field" : "bad field";
    }
}

使用此方法将产生以下html,表示输入无效.至少通过这种方式,我们可以为实际的输入元素设置样式.只是没有消息...

Using this will yield the below html for an invalid input. At least with this we can style the actual input elements. Just not the messages...

<input class="bad field" aria-invalid="">
<div class="validation-message">Identifier too long (16 character limit).</div>

这篇关于在ASP.NET Core中使用ValidationMessage时,可以添加或更改默认CSS类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆