0
嗨我的模型中有int
類型的字段CellPhone
。排除綁定模型中的字符Asp.net MVC
在視圖中,我在我的CellPhone字段中有一個javascript掩碼。當客戶端發送頁面後,我收到這樣的事情:
555-4789
但是這個值不是一個整型有效值。無論如何,通過在綁定發生之前刪除字符'-'
來通知模型聯編程序,我想「清理」該號碼?
也許DataAnnotation或別的東西?
嗨我的模型中有int
類型的字段CellPhone
。排除綁定模型中的字符Asp.net MVC
在視圖中,我在我的CellPhone字段中有一個javascript掩碼。當客戶端發送頁面後,我收到這樣的事情:
555-4789
但是這個值不是一個整型有效值。無論如何,通過在綁定發生之前刪除字符'-'
來通知模型聯編程序,我想「清理」該號碼?
也許DataAnnotation或別的東西?
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
}
這可能有助於雖然電話號碼存儲爲字符串: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
您需要創建一個自定義'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
需要看看你現在怎麼做。無論如何,你嘗試像controllerContext.HttpContext.Request [「CellPhone」]。替換(「 - 」,「」).ToInt()? – Sam 2014-10-02 00:39:41