资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

asp.netMVC中怎么通过自定义ModelBinder过滤关键字-创新互联

asp.net MVC中怎么通过自定义ModelBinder过滤关键字,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

成都创新互联公司专注于企业全网整合营销推广、网站重做改版、清远网站定制设计、自适应品牌网站建设、H5响应式网站商城网站开发、集团公司官网建设、成都外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为清远等各大城市提供网站开发制作服务。
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MvcApplication1.Models
{
   public class TestModel
   {
     public int TID { get; set; }
  
     [DataType("TName")]
     public string TName { get; set; }
  
     [DataType("TSite")]
     public string TSite { get; set; }
   }
}

然后我们新建一个FilterModelBinder的类,其中内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1
{
   public class FilterModelBinder:DefaultModelBinder
   {
     public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
     {
       var valueShouldFilter = bindingContext.ModelMetadata.DataTypeName;
       if (valueShouldFilter == "TName" || valueShouldFilter == "TSite")
       {
         var resultProvider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
         if (resultProvider != null)
         {
           string result = resultProvider.AttemptedValue;
           result = result.Replace("<", "<").Replace(">", ">");
           return result;
         }
       }
  
       return base.BindModel(controllerContext, bindingContext);
     }
   }
}

第13行,主要是获取我们需要验证的DataTypeName.

第15行,获取需要验证的值,然后替换,最后返回即可.

 上面做完后,在Global.asax中,我们需要指定一下:

protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();

   WebApiConfig.Register(GlobalConfiguration.Configuration);
   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   RouteConfig.RegisterRoutes(RouteTable.Routes);
   BundleConfig.RegisterBundles(BundleTable.Bundles);

   ModelBinders.Binders.DefaultBinder = new FilterModelBinder();
}

这样,我们就能使用我们自己的ModelBinder了,下面开始测试:

asp.net MVC中怎么通过自定义ModelBinder过滤关键字

我们输入的内容如上图所示,当点击”添加”按钮的时候,确弹出如下的错误提示:

asp.net MVC中怎么通过自定义ModelBinder过滤关键字

看来,系统会自动检测我们的输入值,发现有非法字符,会弹出错误提示,还好我们可以通过web.config配置一下,让其通过验证:

打开最外层的Web.config,输入以下节点:


  
  
  
  
  

然后保存,运行,我们看到,系统成功跑了起来,最后的结果如下:

asp.net MVC中怎么通过自定义ModelBinder过滤关键字

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联网站建设公司,的支持。


文章名称:asp.netMVC中怎么通过自定义ModelBinder过滤关键字-创新互联
标题网址:http://cdkjz.cn/article/doshgc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220