开发者

Get DisplayName attribute from an MVC2 Model's Property

So, I've got a contact form in my MVC 2 application.

I'd like to programatically email all properties of my "ContactModel".

Here is what I'd like to do in psuedo-ish code:

[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>";

        /* ******开发者_JS百科******************************************* */
        /* 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("to@example.com", "from@example.com", "Subject of Message ", htmlMessage.ToString() );
        TempData["message"] = "You are awesome!";
        return RedirectToAction("Contact", "Home");
    }
}

In case it matters...ContactModel sets up the DisplayName attributes like this:

[DisplayName("First Name")]
public string FirstName {get; set ;}

I'd like to keep this nice and DRY by not repeating the DisplayName names.

Specifically, I'd like to enumerate over each property in my ContactModel, get its DisplayName, and get its submitted value.


You'll need to use reflection over the object's properties and their custom attributes to get their name/value pairs.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜