Gio*_*lbo 23 validation asp.net-mvc
当我使用UpdateModel或TryUpdateModel时,MVC框架足够聪明,可以知道您是否尝试将null传入值类型(例如,用户忘记填写所需的Birth Day字段).
不幸的是,我不知道如何覆盖默认消息"需要一个值".在总结中更有意义的事情("请输入您的出生日").
必须有一种方法可以做到这一点(没有编写过多的解决方法),但我找不到它.有帮助吗?
编辑
此外,我想这也是无效转换的问题,例如BirthDay ="Hello".
小智 19
通过扩展DefaultModelBinder创建自己的ModelBinder:
public class LocalizationModelBinder : DefaultModelBinder
Run Code Online (Sandbox Code Playgroud)
覆盖SetProperty:
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
foreach (var error in bindingContext.ModelState[propertyDescriptor.Name].Errors.
Where(e => IsFormatException(e.Exception)))
{
if (propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)] != null)
{
string errorMessage =
((TypeErrorMessageAttribute)propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)]).GetErrorMessage();
bindingContext.ModelState[propertyDescriptor.Name].Errors.Remove(error);
bindingContext.ModelState[propertyDescriptor.Name].Errors.Add(errorMessage);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
添加函数bool IsFormatException(Exception e)以检查Exception是否是FormatException:
if (e == null)
return false;
else if (e is FormatException)
return true;
else
return IsFormatException(e.InnerException);
Run Code Online (Sandbox Code Playgroud)
创建一个Attribute类:
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class TypeErrorMessageAttribute : Attribute
{
public string ErrorMessage { get; set; }
public string ErrorMessageResourceName { get; set; }
public Type ErrorMessageResourceType { get; set; }
public TypeErrorMessageAttribute()
{
}
public string GetErrorMessage()
{
PropertyInfo prop = ErrorMessageResourceType.GetProperty(ErrorMessageResourceName);
return prop.GetValue(null, null).ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
将属性添加到要验证的属性:
[TypeErrorMessage(ErrorMessageResourceName = "IsGoodType", ErrorMessageResourceType = typeof(AddLang))]
public bool IsGood { get; set; }
Run Code Online (Sandbox Code Playgroud)
AddLang是一个resx文件,IsGoodType是资源的名称.
最后将其添加到Global.asax.cs Application_Start中:
ModelBinders.Binders.DefaultBinder = new LocalizationModelBinder();
Run Code Online (Sandbox Code Playgroud)
干杯!
使用DefaultModelBinder,可以覆盖默认的必需错误消息,但不幸的是,它将全局应用,恕我直言使其完全无用.但如果你决定这样做,那么如何:
PropertyValueRequired和一些值声明一个新的字符串资源在Application_Start中添加以下行:
DefaultModelBinder.ResourceClassKey = "Messages";
Run Code Online (Sandbox Code Playgroud)正如您所看到的,您要验证的模型属性与错误消息之间没有任何关联.
总之,最好编写自定义验证逻辑来处理这种情况.一种方法是使用可空类型(System.Nullable <TValueType>),然后:
if (model.MyProperty == null ||
/** Haven't tested if this condition is necessary **/
!model.MyProperty.HasValue)
{
ModelState.AddModelError("MyProperty", "MyProperty is required");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33919 次 |
| 最近记录: |