TrimToDBCModelBinder.cs
1 //一定要使用using System.Web.Mvc下的DefaultModelBinder 2 public class TrimToDBCModelBinder : DefaultModelBinder 3 { 4 5 public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 6 { 7 object value = base.BindModel(controllerContext, bindingContext); 8 if(value is string) 9 { 10 string strValue = (string)value; 11 string value2 = ToDBC(strValue).Trim(); 12 return value2; 13 } 14 else 15 { 16 return value; 17 } 18 } 19 20 /// <summary> 全角转半角的函数(DBC case) </summary> 21 /// <param name="input">任意字符串</param> 22 /// <returns>半角字符串</returns> 23 ///<remarks> 24 ///全角空格为12288,半角空格为32 25 ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 26 ///</remarks> 27 private static string ToDBC(string input) 28 { 29 char[] c = input.ToCharArray(); 30 for (int i = 0; i < c.Length; i++) 31 { 32 if (c[i] == 12288) 33 { 34 c[i] = (char)32; 35 continue; 36 } 37 if (c[i] > 65280 && c[i] < 65375) 38 { 39 c[i] = (char)(c[i] - 65248); 40 } 41 } 42 return new string(c); 43 } 44 45 }
然后在mvc项目的global.asax.cs下的Application_Start()加入
1 ModelBinders.Binders.Add(typeof(string),new TrimToDBCModelBinder()); 2 ModelBinders.Binders.Add(typeof(int), new TrimToDBCModelBinder()); 3 ModelBinders.Binders.Add(typeof(long), new TrimToDBCModelBinder()); 4 ModelBinders.Binders.Add(typeof(double), new TrimToDBCModelBinder());
这样,就可以对string、int、long、double类型起作用了。
来源:https://www.cnblogs.com/dotnetHui/p/8440437.html