【问题标题】:Prefixing Data Annotation Error Message为数据注释错误消息添加前缀
【发布时间】:2018-11-01 12:04:37
【问题描述】:

场景是我有一个我在剃刀表单中多次使用的对象,我需要为错误消息数据属性添加前缀,以便它们在验证摘要中有意义。

快速示例:

public class Person 
{
    [Required(ErrorMessage = "First Name is Required")]
    [StringLength(30, ErrorMessage = "First Name must be 30 characters or less")]
    public string FirstName { get; set; }
}

public class User 
{
    [Required]
    public Person User { get; set; }
    [Required]
    public Person NextOfKin { get; set; }
}

@Html.EditorFor(x => x.User.FirstName, new { htmlAttributes = new { placeholder = "First Name" }})

@Html.EditorFor(x => x.NextOfKin.FirstName, new { htmlAttributes = new { placeholder = "First Name" }})

如果我在表单中使用 User 类,并且 FirstName 在多个位置留空,则错误消息将相同,两者之间没有任何区别。

在这种情况下我最好的选择是什么?

更新:强调需要为多个 ErrorMessage 字符串添加前缀。

谢谢。

【问题讨论】:

  • 您可以制作 viewModel / DTO(Domain transfer object) 类。在侧面添加 User & Person 属性。然后在页面中使用viewModel。

标签: c# asp.net-mvc validation razor


【解决方案1】:

尝试使用客户端的标题属性覆盖表单中的相应验证消息。

 @Html.EditorFor(x => x.FirstName, new { htmlAttributes = new { @class = "form-control", required = "required", title = "User First Name is required"} })
    @Html.ValidationMessageFor(x => x.FirstName,"", new { @class = "text-danger" })
<!-- NextOfKin entry -->
@Html.EditorFor(y => y.FirstName, new { htmlAttributes = new { @class = "form-control", required = "required", title = "Next Of Kin First Name is required"} })
    @Html.ValidationMessageFor(y => y.FirstName,"", new { @class = "text-danger" })

【讨论】:

  • title 属性与 mvc 验证无关(required 属性也被忽略)
  • 这将如何处理多个验证错误消息,例如 required、length、regex 等
  • 我也只使用 ValidationSummary。
猜你喜欢
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
相关资源
最近更新 更多