ASP.NET Core客户端验证中如何获取属性的完整HTML字段Id
解决方案
你可以直接通过ClientModelValidationContext上下文自带的TemplateInfo.GetFullHtmlFieldId方法生成关联属性的完整HTML ID,该方法会自动适配当前模型的嵌套层级前缀,不需要手动拼接处理。
修改你的AddValidation方法代码如下:
public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-mycustomvalidation", errorMessage); // 生成关联属性的完整HTML ID var templateInfo = context.ActionContext.ViewData.TemplateInfo; string fullOtherPropertyId = templateInfo.GetFullHtmlFieldId(_otherPropertyName); MergeAttribute(context.Attributes, "data-val-mycustomvalidation-otherpropertyname", fullOtherPropertyId); }
补充说明
- 原理说明:渲染嵌套模型字段时,
TemplateInfo.HtmlFieldPrefix会自动存储当前字段的层级前缀,比如渲染MyReport.Value1时,前缀值为MyReport,调用GetFullHtmlFieldId方法时会自动把前缀和传入的属性名用下划线拼接,生成和ASP.NET Core默认渲染规则完全一致的ID值,支持任意层级的嵌套模型。 - 注意原代码中的
_otherProperyName存在拼写错误,少了字母t,需要修正为你定义的私有字段名_otherPropertyName。 - 如果编译报错找不到对应类型,可手动添加命名空间引用:
using Microsoft.AspNetCore.Mvc.ViewFeatures;
内容的提问来源于stack exchange,提问作者haagel
相关产品推荐
相关产品推荐

