排除绑定模型Asp.netMVC中的字符

本文关键字:字符 netMVC Asp 绑定 模型 排除 | 更新日期: 2023-09-27 18:25:13

嗨,我的模型中有一个类型为int的字段CellPhone

在视图中,我的CellPhone字段中有一个javascript掩码。当客户发送页面的帖子时,我会收到这样的东西:

555-4789

但是这个值对于int类型来说不是有效的值。无论如何,有没有通知模型绑定器,我想在绑定发生之前通过删除字符'-'来"清除"数字?

也许是DataAnnotation或其他什么?

排除绑定模型Asp.netMVC中的字符

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
}