asp.net MVC利用自定義ModelBinder過濾關(guān)鍵字的方法(附demo源碼下載)
本文實例講述了MVC利用自定義ModelBinder過濾關(guān)鍵字的方法。分享給大家供大家參考,具體如下:
前面一篇主要講解了如何利用ActionFilter過濾關(guān)鍵字,這篇主要講解如何利用自己打造的ModelBinder來過濾關(guān)鍵字。
首先,我們還是利用上一篇《asp.net MVC利用ActionFilterAttribute過濾關(guān)鍵字的方法》中的實體類,但是我們需要加上DataType特性,以便于我們構(gòu)造的ModelBinder通過DataTypeName識別出來:
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的類,其中內(nèi)容如下:
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了,下面開始測試:
我們輸入的內(nèi)容如上圖所示,當點擊”添加”按鈕的時候,確彈出如下的錯誤提示:
看來,系統(tǒng)會自動檢測我們的輸入值,發(fā)現(xiàn)有非法字符,會彈出錯誤提示,還好我們可以通過web.config配置一下,讓其通過驗證:
打開最外層的Web.config,輸入以下節(jié)點:
<configuration> <system.web> <httpRuntime requestValidationMode="2.0" /> </system.web> <pages validateRequest="false"> </pages> </configuration>
然后保存,運行,我們看到,系統(tǒng)成功跑了起來,最后的結(jié)果如下:
我們可以看到,通過我們自定義的ModelBinder,系統(tǒng)自動將非法字符進行了替換,非常方便。
MVC中處處AOP,現(xiàn)在我們就可以利用現(xiàn)有的知識做一個全局過濾器了。是不是感覺很方便呢?
完整實例代碼點擊此處本站下載。
希望本文所述對大家asp.net程序設(shè)計有所幫助。
相關(guān)文章
asp.net實現(xiàn)調(diào)用帶有輸出參數(shù)的存儲過程實例
這篇文章主要介紹了asp.net實現(xiàn)調(diào)用帶有輸出參數(shù)的存儲過程,結(jié)合實例形式分析了前端基于jQuery的ajax調(diào)用及后臺存儲過程調(diào)用的相關(guān)技巧,需要的朋友可以參考下2016-03-03ASP.NET MVC4中使用Html.DropDownListFor的方法示例
這篇文章主要介紹了ASP.NET MVC4中使用Html.DropDownListFor的方法,結(jié)合實例形式分析了控制器數(shù)據(jù)源及Html.DropDownListFor顯示操作的相關(guān)技巧,需要的朋友可以參考下2016-08-08ASP.NET 連接ACCESS數(shù)據(jù)庫的簡單方法
一段非常簡單的連接ACCESS數(shù)據(jù)庫的實例代碼,有需要的朋友可以參考一下2013-07-07asp.net 獲取目錄下的文件數(shù)和文件夾數(shù)
遍歷一個文件夾中的文件,需要用到DirectoryInfo類中的一個重要的方法GetFileSystemInfos(),此方法返回指定的是與搜索條件相匹配的文件和子目錄的強類型 FileSystemInfo對象的數(shù)組。2010-07-07