Skip to main content
 首页 » 编程设计

c#之不同的验证消息和验证摘要消息

2024年02月20日12kevingrace

我想向用户显示不同的验证消息。一个在验证消息列表中,另一个在我的编辑框附近。我们通过代码来看:
我的模型:

[StringLength(10, ErrorMessage = "{0} cannot be more than {1} characters.")] 
string Name { get; set; } 

在 View 中:

@* in form *@ 
 
@* 
My long message is here: 
"Name cannot be more than 10 characters." 
*@ 
@Html.ValidationSummary(false) 
 
@* 
And my short validation message is here: 
"*" 
*@ 
@Html.TextBoxFor( m=> m.Name) 
@Html.ValidationMessageFor(m => m.Name) 
@* 
But this validation message must be "*" instead of "Name cannot be more than 10 characters." 
*@ 

我还使用了 @Html.ValidationMessageFor(m => m.Name, "ShortMessage"),但是没有用。它会在页面加载后立即显示“ShortMessage”。不是在验证失败之后。

如何实现?我正在使用 MVC4。
任何帮助将不胜感激。

请您参考如下方法:

代替

@Html.ValidationMessageFor(m => m.Name) 

使用

@Html.ValidationMessage("Name", "*") 

这允许您直接在 View 中指定消息,在本例中为星号。