如何在错误消息中显示属性值

时间:2018-11-09 09:24:02

标签: c# validation asp.net-web-api data-annotations model-validation

我正在使用模型验证来显示错误消息。像下面一样

    public class ClientData
{

    [DataMember]
    [MaxLength(10, ErrorMessage = "ERR-ClientSequenceId-02:Enter maximum of 10 characters")]
    public string CSeqId { get; set; }


    [DataMember]
    [Required(ErrorMessage = "ERR-Number-01:Number is required")]
    [RegularExpression(@"^\d{9}$", ErrorMessage = "ERR-Number-02:Enter Valid Number")]
    [MaxLength(9, ErrorMessage = "ERR-Number-03:Maximum 9 digits only allowed")]
    [SampleText("003333330")]
    public string ClientNumber { get; set; }

    [DataMember]
    [MaxLength(2, ErrorMessage = "ERR-STATE-04:State code in 2 characters for the Client Data Address")]
    [RegularExpression(@"[A-Za-z{2}]+$", ErrorMessage = "ERR-STATE-05:Enter a valid Client Data Address State code")]
    [SampleText("AL")]
    public string StateCd { get; set; }
}

此处,错误消息来自 ErrorMessage

但是我想将 CSeqId 值添加到所有ErrorMessage中,例如“ 123 ERR-Number-01:需要数字”。这里的123是CSeqId值。

如何使用模型验证?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在视图中包括此内容:@Html.ValidationMessage("Id")

然后在您的控制器中,检查该值是否为null,如果是,则创建一个自定义模型错误,如下所示:

ModelState.AddModelError("Id", id + " ERR-Number-01: Number is required")

该错误消息将与任何模型状态验证错误一样显示。