Send a Posted Form through Modelbinder as Email

In C# MVC

Montag, 7. Juli 2014

Sometimes you just want to send the content of a form as email to someone. When you bind to a Model you can use a function like this:

public string GetPostedInfoAsPlainText(object post)
{
   StringBuilder sb = new StringBuilder();
   PropertyInfo[] info = post.GetType().GetProperties();
   foreach (var el in info)
   {
       string displayname = el.Name;
       string displayvalue = "";

       // Use DisplayAttribute for name if it exists
       object[] a = el.GetCustomAttributes(typeof(DisplayAttribute), true);
       if (a.Length > 0)
       {
            displayname = ((DisplayAttribute)a[0]).Name;
            if (displayname == null)
                 displayname = el.Name;
       }

       // Depending on Type, ad more...
       switch (el.PropertyType.Name)
       {
             case "Int32":
                 int i = (int)el.GetValue(post, null);
                 displayvalue = i.ToString();
                 break;
             default:
                 string s = el.GetValue(post, null) as string;
                 if (!String.IsNullOrEmpty(s))
                 {
                      displayvalue = s;
                 }
                 break;
        }
        if (displayvalue != "")
        {
            sb.Append(String.Format("{0,-20}", displayname) + " : " + displayvalue + "\n");
        }
    }
return sb.ToString();
} 

 DisplayAttribute is used to get a speaking name for each Field. If you need to send only spefific Fields you could use a CustomAttribute for that.