You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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);
}

补充说明

  1. 原理说明:渲染嵌套模型字段时,TemplateInfo.HtmlFieldPrefix会自动存储当前字段的层级前缀,比如渲染MyReport.Value1时,前缀值为MyReport,调用GetFullHtmlFieldId方法时会自动把前缀和传入的属性名用下划线拼接,生成和ASP.NET Core默认渲染规则完全一致的ID值,支持任意层级的嵌套模型。
  2. 注意原代码中的_otherProperyName存在拼写错误,少了字母t,需要修正为你定义的私有字段名_otherPropertyName。
  3. 如果编译报错找不到对应类型,可手动添加命名空间引用:using Microsoft.AspNetCore.Mvc.ViewFeatures;

内容的提问来源于stack exchange,提问作者haagel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:06:03