Reputation: 3784
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?
Upvotes: 0
Views: 628
Reputation: 567
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
}
Upvotes: 1