您好我的模型中有CellPhone
类型的字段int
。
在视图中,我的CellPhone字段中有一个javascript掩码。当客户端发送页面的帖子时,我会收到类似的内容:
555-4789
但是这个值对于int类型来说不是有效值。无论如何,通过在绑定发生之前删除字符'-'
来通知模型绑定器我想要“清理”数字?
可能是DataAnnotation还是别的什么?
答案 0 :(得分:1)
Use custom model binder for that-
public class yourmodel
{
public int cellphone{get;set;}
}
Define custom model binder as
public class CustomBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string[] phoneArray= request.Form.Get("CellPhone").split('-');
string phone=phoneArray[0]+phoneArray[1];
return new yourmodel
{
cellphone= convert.ToInt32(phone)
};
}
}
then in app_start register new created binder as
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(yourmodel), new CustomBinder());
}
and in controller
[HttpPost]
public ActionResult Index([ModelBinder(typeof(CustomBinder))] yourmodel model)
{
//..processing code
}