ASP.NET MVC IModelBinder应用
ASP.NET MVC5 暂时找到这种全局性的解决方案 参考 MVC项目开发中那些用到的知识点(MVC IModelBinder)
事情的起因
利用jQuery $.ajax作POST提交, 对发送参数在B端做了 escape(item.value.HTMLEncode()) ,所以在C端对接收到参数要做 UrlDecode(); 势必在action接收modle时有大量的重复性冗余代码,如下面
public string Create(tbiz_movieEntity movie) { if (ModelState.IsValid) { tbiz_movieBLL movieBLL = new tbiz_movieBLL(); movie.MovieFileName = movie.MovieFileName.UrlDecode(); //HttpUtility.HtmlDecode(movie.MovieFileName); movie.MovieName = movie.MovieName.UrlDecode(); movie.CreateTime = DateTime.Now; movieBLL.Addtbiz_movieEntity(movie);
使用自定义IModelBinder类进行解决
\Models\CustomBinder.cs
public class CustomBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { object obj = Activator.CreateInstance(bindingContext.ModelType); foreach (PropertyInfo p in bindingContext.ModelType.GetProperties()) { ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(p.Name); if (vpResult != null) { object value = vpResult.ConvertTo(p.PropertyType); if (value.ToString().IndexOf("%") > -1 && value.GetType() == typeof(string)) { object decodeVal = value.ToString().UrlDecode(); p.SetValue(obj, decodeVal, null); } else { p.SetValue(obj, value, null); } } } return obj; } }
代码重构
[HttpPost] public string Create([ModelBinder(typeof(CustomBinder))]tbiz_movieEntity movie)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步