2017-01-24 15 views
0

この質問は以前に尋ねられている必要がありますが見つかりませんでした。属性に基づくモデルのプロパティの処理

私はカスタムモデルのバインダーを作成することで、ユーザーが入力したデータを処理できることを知っています。文字列のプロパティをトリミングする例があります。ここにその例があります:ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?

私の質問は、カスタム属性を使用して処理するかどうかを制御する方法です。

例えば、私が唯一の場合、私は以下のようにそれを示す属性持って自動的に文字列プロパティの最初の文字を大文字にする必要がありますので、この例では

public class MyModel 
{ 
    [CapitalizeFirstLetter] 
    public string FirstName { get; set; } 

    [CapitalizeFirstLetter] 
    public string LastName { get; set; } 

    public string UserName { get; set; } 
} 

を姓と名のプロパティ3つはすべて文字列プロパティですが、処理されますがユーザー名は取得されません。

どうすれば対応できますか?

+0

私はあなたが提供することができ、本当に「処理処理したりしないようにするとき」、あなたはここに求めているものを理解しませんより良い説明? – MrVoid

答えて

1

あなたはそれが設定した特定の属性を持っているかどうかを確認するには、プロパティをチェックするとよいでしょう:

public class CapitalizeFirstLetterModelBinder : DefaultModelBinder 
{ 
    protected override void SetProperty(
     ControllerContext controllerContext, 
     ModelBindingContext bindingContext, 
     System.ComponentModel.PropertyDescriptor propertyDescriptor, 
     object value) 
    { 
     if (propertyDescriptor.Attributes.Any(att => typeof(att) == typeof(CapitalizeFirstLetterAttribute)) 
     { 
      var stringValue = (string)value; 
      if (!string.IsNullOrWhiteSpace(stringValue)) 
      { 
       value = stringValue.First().ToString().ToUpper() + stringValue.Substring(1); 
      } 
      else 
      { 
       value = null; 
      } 
     } 

     base.SetProperty(controllerContext, bindingContext, 
         propertyDescriptor, value); 
    } 
} 
関連する問題