Asp.net

數據輸入後修剪字元串的最佳方法。我應該創建自定義模型綁定器嗎?

  • November 11, 2009

我正在使用 ASP.NET MVC,我希望在將所有使用者輸入的字元串欄位插入數據庫之前對其進行修剪。由於我有許多數據輸入表單,我正在尋找一種優雅的方式來修剪所有字元串,而不是顯式地修剪每個使用者提供的字元串值。我很想知道人們如何以及何時修剪字元串。

我考慮過可能創建一個自定義模型綁定器並在那裡修剪任何字元串值……這樣,我所有的修剪邏輯都包含在一個地方。這是一個好方法嗎?是否有任何程式碼範例可以做到這一點?

 public class TrimModelBinder : DefaultModelBinder
 {
   protected override void SetProperty(ControllerContext controllerContext, 
     ModelBindingContext bindingContext, 
     System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
   {
     if (propertyDescriptor.PropertyType == typeof(string))
     {
       var stringValue = (string)value;
       if (!string.IsNullOrWhiteSpace(stringValue))
       {
         value = stringValue.Trim();
       }
       else
       {
         value = null;
       }
     }

     base.SetProperty(controllerContext, bindingContext, 
                         propertyDescriptor, value);
   }
 }

這段程式碼怎麼樣?

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();

設置 global.asax Application_Start 事件。

引用自:https://stackoverflow.com/questions/1718501