我正在尝试通过更改 TagHelper 中 HTML 子元素的类来实现服务器端验证。 TagHelper 是“kendo-datepicker”,但是当前代码修改了“span”标签的类,我想修改子“input”标签的类。
经过一些研究,似乎 GetChildContentAsync 可能有用,但我所有使用它的尝试都失败了。
标签帮助器:
[HtmlTargetElement("kendo-datepicker")]
[HtmlTargetElement("select")]
[HtmlTargetElement("input")]
public class ValidationErrorClassTagHelper : TagHelper
{
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
//output.Attributes.ContainsName("class")
if (context.TagName == "kendo-datepicker")
{
TagHelperAttribute taghelperAttribute = context.AllAttributes["for"];
if (taghelperAttribute != null)
{
ModelExpression modelExpression = (ModelExpression)taghelperAttribute.Value;
ViewContext.ViewData.ModelState.TryGetValue(modelExpression.Name, out ModelStateEntry entry);
if (entry != null && entry.Errors.Any())
{
output.Attributes.SetAttribute("class", "form-control " + "is-invalid");
}
}
}
}
}
当前(不正确)HTML 输出:
<span class="k-datepicker k-input form-control is-invalid k-input-solid k-input-md k-rounded-md" style=""><input class="form-control k-input-inner valid" required="" data-val="true" data-val-required="Enter the date observed." id="ADR_Date" name="ADR.Date" type="text" value="6/07/2023" data-role="datepicker" role="combobox" aria-expanded="false" aria-haspopup="grid" aria-controls="ADR_Date_dateview" autocomplete="off" aria-disabled="false" aria-readonly="false" aria-describedby="ADR_Date-error" aria-invalid="false"><button aria-label="select" tabindex="-1" class="k-input-button k-button k-icon-button k-button-md k-button-solid k-button-solid-base" type="button" role="button"><span class="k-icon k-i-calendar k-button-icon"></span></button></span>
一个非常原始的想法就是去做
TagHelperContent innerContent = await output.GetChildContentAsync();
然后通过
GetContent
获取内容作为 string
,然后解析这个 string
,然后在添加 SetContent
后解析 class
。这无疑是一个肮脏的解决方案,只有在我们无能为力的情况下才应该采用。
或者,您可以查看
context.Items
并查看某个键下是否有输入。如果是这样,那么您可以使用那个。