2014-10-01 56 views
0

嗨我的模型中有int类型的字段CellPhone排除绑定模型中的字符Asp.net MVC

在视图中,我在我的CellPhone字段中有一个javascript掩码。当客户端发送页面后,我收到这样的事情:

555-4789 

但是这个值不是一个整型有效值。无论如何,通过在绑定发生之前删除字符'-'来通知模型联编程序,我想“清理”该号码?

也许DataAnnotation或别的东西?

+0

这可能有助于虽然电话号码存储为字符串:http://stackoverflow.com/questions/9840337/mvc-validation-for-us-phone-number-000-000-0000-or- 000-000-0000 – Papa 2014-10-01 23:50:22

+0

您需要创建一个自定义'ModelBinder'。 [这个答案](http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo)规定一个修剪空白的例子,但我相信你可以适应你的需要 – 2014-10-01 23:50:35

+0

需要看看你现在怎么做。无论如何,你尝试像controllerContext.HttpContext.Request [“CellPhone”]。替换(“ - ”,“”).ToInt()? – Sam 2014-10-02 00:39:41

回答

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 
}