2010-12-28 13 views
2

MVC 2アプリケーションで連絡先フォームを取得しました。MVC2モデルのプロパティからDisplayName属性を取得

ContactModel」のすべてのプロパティをプログラムで電子メールで送信したいと考えています。

[DisplayName("First Name")] 
public string FirstName {get; set ;} 
ContactModelはこのよう DisplayName属性を設定します...それが重要な場合は

[HttpPost] 
public ActionResult Contact(ContactModel model) 
    if(!ModelState.IsValid){ 
     TempData["errorMessage"] = "You are a failure!"; 
     return View(model); 
    } 
    else{ 
     var htmlMessage = new StringBuilder("<table>"); 
     const string templateRow = "<tr><td>{0}: </td><td><strong>{1}</strong></td></tr>"; 

     /* ************************************************* */ 
     /* This is the part I need some serious help with... */ 
     /* ************************************************* */ 
     foreach(var property in someEnumerableObjectBasedOnMyModel){ 
      htmlMessage.AppendFormat(templateRow, 
       // the display name for the property 
       property.GetDisplayName(), 
       // the value the user input for the property (HTMLEncoded) 
       model[property.Key] 
      ); 
     } 
     /* ************************************************* */ 

     htmlMessage.Append("</table>"); 

     // send the message... 
     SomeMagicalEmailer.Send("[email protected]", "[email protected]", "Subject of Message ", htmlMessage.ToString()); 
     TempData["message"] = "You are awesome!"; 
     return RedirectToAction("Contact", "Home"); 
    } 
} 

:ここ

は、私は擬似っぽいコードでやってみたいものです

私はDisplayNameの名前を繰り返さないことでこれをうまく保ちたいと思います。

具体的には、ContactModelの各プロパティを列挙し、そのDisplayNameを取得し、送信された値を取得したいと思います。

答えて

3

名前と値のペアを取得するには、オブジェクトのプロパティとカスタム属性のリフレクションを使用する必要があります。

foreach (var property in typeof(ContactModel).GetProperties()) 
{ 
    var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute),false) 
          .Cast<DisplayNameAttribute>() 
          .FirstOrDefault(); 
    if (attribute != null) 
    { 
      var value = property.GetValue(model, null); 
      var name = attribute.DisplayName; 

      htmlMessage.AppendFormat(templateRow, name, value); 
    } 
} 
+0

+1これは素晴らしいです。反射なしでそれを行う方法はありますか?アプリはMediumTrustで実行されます。 : -/ –

+0

@David - 属性を直接使用しません。 – tvanfosson

+2

passersの場合: 'ModelMetadata.FromLambdaExpression (式、新しいViewDataDictionary (モデル)).DisplayName;' –

関連する問題