0

Hi I have a field CellPhone of type int in my model.

In the view I have a javascript mask in my CellPhone field. When the client send the post of the page I receive something like that:

555-4789

But this value is not valid value for a int type. There is anyway to notify the model binder that I want to "clean" the number by removing the character '-' before binding happens?

Maybe a DataAnnotation or something else?

Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81
  • This may help though the phone number is stored as string: http://stackoverflow.com/questions/9840337/mvc-validation-for-us-phone-number-000-000-0000-or-000-000-0000 – Papa Oct 01 '14 at 23:50
  • You need to create a custom `ModelBinder`. [This answer](http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo) provides an example for trimming white space but I'm sure you can adapt to for you needs –  Oct 01 '14 at 23:50
  • Need to see how you do it right now. Anyway did you try something like controllerContext.HttpContext.Request["CellPhone"].Replace("-", "").ToInt() ? – Sam Oct 02 '14 at 00:39

1 Answers1

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
}
Mahesh
  • 567
  • 2
  • 14