0

我是实体框架的新手,我使用模型优先方法创建了一个 EDM,并使用数据注释应用了验证,一切正常,但所有验证都显示在一个地方,但我想在相应字段旁边显示验证错误消息。

我写的代码如下

public partial class Hardware_services_repairs
{
public class hardwaremetadata
{
[Required]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage="Numbers and Special characters are not      allowed")]
public string CompanyName { get; set; }
[Required]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage="Numbers and Special characters are not allowed")]
public string ContactName { get; set; }
//[Required]
[RegularExpression(@"^[0-9+-]+$",ErrorMessage="Only numbers are allowed")]
public string PhoneNumber { get; set; }
//[Required]
[RegularExpression(@"^[0-9+-]+$", ErrorMessage = "Only numbers are allowed")]
public string MobileNumber { get; set; }
//[Required]
[RegularExpression(@"^[A-Za-z0-9#: ]+$", ErrorMessage = "Special Characters are not allowed")]
public string Address { get; set; }
}
}

输出如下图

List of validation errors
Numbers and Special characters are not allowed
Numbers and Special characters are not allowed
Only numbers are allowed
Only numbers are allowed
Special Characters are not allowed

但是我希望每个错误消息都单独出现在相应的字段旁边,请让我解决

提前致谢

4

2 回答 2

0

您不必添加 @Html.validationSummary

向要验证的每个字段添加一个validationMessageFor 并显示验证错误

<div>
    @Html.LabelFor(model => model.CompanyName) 
</div>
<div>
    @Html.EditorFor(model => model.CompanyName)
    @Html.ValidationMessageFor(model => model.CompanyName)
</div>
于 2013-07-17T06:53:40.960 回答
0

也许,问题出在您的视图中。

方法“ValidationSummary”的参数“excludePropertyErrors”必须设置为“true”:

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true)

然后,对于每个字段,您必须编写如下内容:

<div>
    @Html.LabelFor(model => model.CompanyName) 
</div>
<div>
    @Html.EditorFor(model => model.CompanyName)
    @Html.ValidationMessageFor(model => model.CompanyName)
</div>
于 2013-06-24T16:08:10.713 回答