好吧,这是我的问题。今天,我决定实现一种机制,使我可以更轻松地实现视图中的字段。我在剃刀页面中有一个项目,我在服务器端对必填字段进行验证。 例如,在页面模型中我有以下验证:
if (string.IsNullOrEmpty(Record.Name))
ModelState.AddModelError(key: "Record.Name", errorMessage: RS_Relationships.name_field_required);
这就是我构建这个领域的方式:
<div class="form-group mx-2 my-2 w-full sm:w-1/2 md:w-1/3 lg:w-1/4">
<label asp-for="Record.Name" class="block"></label>
<input asp-for="Record.Name" class="form-input w-full bg-yellow-100 dark:bg-yellow-100 dark:text-black"/>
<span asp-validation-for="Record.Name" class="text-red-600"></span>
</div>
这对我来说非常有效。
但是通过实现以下标记帮助器,跨度不再显示名称字段是必需的错误消息。
[HtmlTargetElement(tag: "text-required-field")]
public class StringRequiredFieldHelper : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression? For { get; set; }
[HtmlAttributeName("asp-validation-for")]
public ModelExpression? Validation { get; set; }
[HtmlAttributeName("label-for")]
public string? LabelName { get; set; }
public override void Process(TagHelperContext Context, TagHelperOutput Output)
{
var container = new TagBuilder("div");
var label = new TagBuilder(tagName: "label");
label.Attributes["for"] = For?.Name;
label.AddCssClass("block");
label.InnerHtml.Append(LabelName?.ToString() ?? string.Empty);
var input = new TagBuilder(tagName: "input");
input.Attributes["name"] = For?.Name;
input.Attributes["id"] = For?.Name;
input.Attributes["value"] = For?.Model?.ToString();
input.AddCssClass("form-input w-full bg-yellow-100 dark:bg-yellow-100 dark:text-black");
input.Attributes["type"] = "text";
var validation = new TagBuilder(tagName: "span");
validation.AddCssClass("text-red-600 field-validation-error");
validation.Attributes["data-valmsg-for"] = Validation?.Name;
validation.Attributes["data-valmsg-replace"] = "true";
container.InnerHtml.AppendHtml(content: label);
container.InnerHtml.AppendHtml(content: input);
container.InnerHtml.AppendHtml(content: validation);
Output.Content.SetHtmlContent(htmlContent: container);
}
}
领域:
<text-required-field asp-for="Record.Name" asp-validation-for="Record.Name" label-for="@RS_Relationships.name"></text-required-field>
有人可以帮我解决这个错误吗?
之后: 在此输入图片描述
之前: 在此输入图片描述
解决了。
简单的解决方案,你只需要将这个验证实现到tagHelper中:
var modelState = ViewContext?.ViewData.ModelState;
if (modelState != null
&& For != null
&& modelState.TryGetValue(For.Name, out ModelStateEntry? entry)
&& entry.Errors.Count > 0)
{
validation.InnerHtml.Append(unencoded: entry.Errors[0].ErrorMessage);
}