mik*_*kal 1 c# asp.net-mvc asp.net-core-mvc tag-helpers
我正在尝试制作一个绑定到当前 ModelState 的自定义 TagHelper,就像
<input asp-for="this_part" />
Run Code Online (Sandbox Code Playgroud)
我想从我的自定义 TagHelper 类中进行一些 ModelState 验证。
尝试搜索Github存储库,但无法查明这一确切行为。有人找到办法做到这一点吗?
谢谢!
我不确定您到底在寻找什么,但DefaultHtmlGenerator 对验证消息做了类似的事情。
您可以ModelState通过以下方式访问ViewContext(示例改编自ValidationMessageTagHelper.cs):
[TargetElement("span", Attributes = AttributeName)]
public class YourTagHelper : TagHelper
{
private const string AttributeName = "your-for";
[ViewContext]
[HtmlAttributeNotBound]
protected internal ViewContext ViewContext { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var modelState = ViewContext.ViewData.ModelState;
// Your logic here
}
}
Run Code Online (Sandbox Code Playgroud)
从您的评论中,您提到您需要智能感知来映射到模型属性。ValidationMessageTagHelper.cs使用此属性执行此操作:
[HtmlAttributeName(ValidationForAttributeName)]
public ModelExpression For { get; set; }
Run Code Online (Sandbox Code Playgroud)