我已经按照这篇文章在.NET Core 2.0中开发了自定义form-input
标记帮助程序:Custom ViewComponent with asp-for as parameter
HTML表单:
@model PersonModel
<form asp-controller="Home" asp-action="Test" method="post">
<form-input asp-for="Name" />
<div asp-validation-summary="All"></div>
<button type="submit"></button>
</form>
Model类:
public class PersonModel
{
[Required]
public string Name { get; set; }
}
自定义标签助手:
[HtmlTargetElement("form-input")]
public class FormInput : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
private readonly HtmlHelper _htmlHelper;
private readonly HtmlEncoder _htmlEncoder;
public FormInput(IHtmlHelper htmlHelper, HtmlEncoder htmlEncoder)
{
_htmlHelper = htmlHelper as HtmlHelper;
_htmlEncoder = htmlEncoder;
}
[ViewContext]
public ViewContext ViewContext
{
set => _htmlHelper.Contextualize(value);
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
var partial = await _htmlHelper.PartialAsync("~/Views/FormInput.cshtml", new FormInputVM { For = For });
var writer = new StringWriter();
partial.WriteTo(writer, _htmlEncoder);
output.Content.SetHtmlContent(writer.ToString());
}
}
FormInput.cshtml
部分视图:
@model ModelExpression
<input asp-for="Model" name="@Model.Name" />
生成的HTML如下所示:
<form method="post" action="/Home/Test">
<input name="Name" type="text" id="Model" value="">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<button type="submit"></button>
</form>
当我更改输入中的值并提交表单时,一切进展顺利:将模型以正确的值正确发送到控制器。
我现在想使用我在[Required]
字段上添加的Name
注释来显示模型验证错误,但是它似乎不起作用。我们可以看到上面生成的input
元素没有验证属性。
您知道如何使用我使用的自定义标签帮助程序获得以下生成的输入吗?
<input type="text" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" value=""/>
非常感谢。