0

How do I get an enums Display Name in my controller so that I can use it in emails?

NOTE: I need the Display Name in my controller & not a view..

Currently my email displays like:

Age Range: age2130

But I want it to use the Display Name instead like:

Age Range: 21-30

Here is an example of my modal:

    public enum AgeGroups
    {
        [Display(Name = "21-30")]
        age2130,
        [Display(Name = "31-40")]
        age3140,
        [Display(Name = "41-50")]
        age4150,
        [Display(Name = "51+")]
        age51plus
    }
    [Required]
    [Display(Name = "Age Group")]
    public AgeGroups? AgeGroup { get; set; }

Here is the email section from my controller:

string fromURL = this.Request.ServerVariables["http_referer"];
string userIpAddress = this.Request.ServerVariables["REMOTE_ADDR"];
var subject = "New enquiry from {0} {1}";
var body = "<p>You have a new enquiry from: {0}</p><p>Interested In: {1}</p><p>First Name: {2}</p><p>Last Name: {3}</p><p>Phone Number: {4}</p><p>Email Address: {5}</p><p>Suburb: {6}</p><p>Post Code: {7}</p><p>Age Group: {8}</p><p>Found Us By: {9}</p><p>Join Mailing List: {10}</p><p>IP Address: {11}</p>";
var replyto = model.EmailAddress;
var message = new MailMessage();
message.To.Add(new MailAddress("test@test.com"));
message.ReplyToList.Add(new MailAddress(replyto));
message.Subject = string.Format(subject, model.FirstName, model.LastName);
message.Body = string.Format(body, fromURL, model.InterestedIn, model.FirstName, model.LastName, model.PhoneNumber, model.EmailAddress, model.Suburb, model.PostCode, model.AgeGroup, model.FoundUs, model.JoinMailingList, userIpAddress);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
    await smtp.SendMailAsync(message);
    return new HttpStatusCodeResult(HttpStatusCode.OK);
}
MWD
  • 1,632
  • 2
  • 18
  • 39
  • The duplicate question is in a view - I need it in my controller.. – MWD Sep 12 '15 at 09:22
  • It makes no difference. You need to use reflection to get the value of the `[Display]` attribute as shown in the code in the answers –  Sep 12 '15 at 09:37
  • Please link to the code answer you are talking about that has specific info on displaying it in the controller as I can't see it. Thx. – MWD Sep 12 '15 at 10:23
  • 1
    They are all very similar. You create a extension method. For example the 3rd answer has one called `GetDisplayName()`. Then you would use it as `string displayName = model.AgeGroup.GetDisplayName();` –  Sep 12 '15 at 10:31
  • Thank you - much appreciated :) – MWD Sep 12 '15 at 10:37

0 Answers0