您的位置:首页 > 其它

如何修改默认的ModelState错误提示:字段{0}必须是一个数字

2012-06-26 16:46 309 查看
当使用ViewModel并且某个属性为int或decimal等值类型时,我们如果使用Html.TextBoxFor或Html.TextBox方法,则输入了非数字字符,后台会自动校验,并提示:字段{0}必须是一个数字。

有时候我们需要自定义这个提示,具体可自定义一个ModelBinder类,继承自DefaultModelBinder,重写BindModel方法:

public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var v = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
decimal parsedValue = 0m;
if (!decimal.TryParse(v.AttemptedValue, out parsedValue)) {
var error = @"'{0}'不是正确的数值格式";
bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format(error, v.AttemptedValue, bindingContext.ModelMetadata.DisplayName));
}
return base.BindModel(controllerContext, bindingContext);
}
}


然后在Application_Start事件中注册一下即可:

ModelBinders.Binders.Add(typeof(decimal), new Ichari.Common.MvcExtended.DecimalModelBinder());


说明:此方法只针对后台的Model默认校验,如果启用前台unobtrusive js的话,需要自定义客户端的Validate规则,也可参考文章:http://greenicicleblog.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐