C# 在绑定模型Asp.net MVC中排除字符
嗨,我的模型中有一个C# 在绑定模型Asp.net MVC中排除字符,c#,asp.net,.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,.net,Asp.net Mvc,Asp.net Mvc 4,嗨,我的模型中有一个手机类型的字段int 在视图中,我的手机字段中有一个javascript掩码。当客户端发送页面帖子时,我会收到如下内容: 555-4789 但此值不是int类型的有效值。无论如何,在绑定之前,是否要通知模型绑定器我要通过删除字符'-'来“清理”数字 可能是数据注释或其他什么?尽管电话号码存储为字符串,但这可能会有所帮助:您需要创建一个自定义的ModelBinder。提供了一个修剪空白的示例,但我相信您可以根据需要进行调整,以了解您现在是如何做到这一点的。无论如何,您是否尝试
手机类型的字段int
在视图中,我的手机字段中有一个javascript掩码。当客户端发送页面帖子时,我会收到如下内容:
555-4789
但此值不是int类型的有效值。无论如何,在绑定之前,是否要通知模型绑定器我要通过删除字符'-'
来“清理”数字
可能是数据注释或其他什么?尽管电话号码存储为字符串,但这可能会有所帮助:您需要创建一个自定义的ModelBinder
。提供了一个修剪空白的示例,但我相信您可以根据需要进行调整,以了解您现在是如何做到这一点的。无论如何,您是否尝试过类似controllerContext.HttpContext.Request[“手机”].Replace(“-”,“).ToInt()?
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
}