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)

 

posted @ 2020-10-30 16:30  轴轴  阅读(174)  评论(0编辑  收藏  举报