在MVC的世界里,我有一个视图模型...
public class MyViewModel{
[Required]
public string FirstName{ get; set; } }在我看来,...and这类事情...
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>我的问题:如果我提交此表单而不提供姓名,则会收到以下消息“FirstName字段是必需的”
好的。所以,我去把我的属性改成...
[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; } ..and现在得到“名字字段是必需的”
到目前为止一切都很好。
因此,现在我希望错误消息显示"First Name Blah“。我如何才能覆盖默认消息以显示DisplayName +“Blah",而不是用下面的内容注释所有属性
[Required(ErrorMessage = "First Name Blah Blah")]干杯,
ETFairfax
发布于 2009-12-19 06:49:51
public class GenericRequired: RequiredAttribute
{
public GenericRequired()
{
this.ErrorMessage = "{0} Blah blah";
}
}发布于 2012-03-29 03:10:33
看起来RequiredAttribute并没有实现IClientValidatable,所以如果你覆盖了RequiredAttribute,它就会破坏客户端验证。
这就是我所做的,它起作用了。希望这对某些人有帮助。
public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
public CustomRequiredAttribute()
{
this.ErrorMessage = "whatever your error message is";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "required"
};
}
}发布于 2014-04-20 15:39:32
这里有一个不用继承RequiredAttribute子类就能做到的方法。只需创建一些属性适配器类。这里我使用的是ErrorMessageResourceType/ErrorMessageResourceName (带有一个资源),但是你可以很容易地设置ErrorMessage,甚至可以在设置它们之前检查是否存在覆盖。
Global.asax.cs:
public class MvcApplication : HttpApplication {
protected void Application_Start() {
// other stuff here ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
}
}
private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValRequired";
}
}
private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValStringLength";
}
}本例将创建一个名为Resources.resx的资源文件,并将ValRequired作为新的必需默认消息,将ValStringLength作为字符串长度超过默认消息。请注意,对于这两个字段,您可以使用[Display(Name = "Field Name")]来设置,{0}将接收字段的名称。
https://stackoverflow.com/questions/1808097
复制相似问题