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("[email protected]")); 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); } 
5
  • The duplicate question is in a view - I need it in my controller.. Commented Sep 12, 2015 at 9: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 Commented Sep 12, 2015 at 9: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. Commented Sep 12, 2015 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(); Commented Sep 12, 2015 at 10:31
  • Thank you - much appreciated :) Commented Sep 12, 2015 at 10:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.