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

        /* ************************************************* */
        /* 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.

Answers


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 );
     }
}

Need Your Help

same size (widthxheight) for input and select

html css

How can I create input[text] and select of same height and width. It shld be same in all browsers?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.