Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-friendly Property Names in .NET, like those in Rails

In Ruby on Rails, there's a YAML file in the configuration that lets you define plain-English versions of your model property names. Actually, it lets you define plain-any-language versions: it's part of the internationalization stuff, but most people use it for things like displaying model validation results to the user.

I need that kind of functionality in my .NET MVC 4 project. The user submits a form and gets an email of pretty much everything they posted (the form gets bound to a model). I wrote a helper method to dump out an HTML table of property/value pairs by reflection, e.g.

foreach (PropertyInfo info in obj.GetType()
    .GetProperties(BindingFlags.Public | 
                   BindingFlags.Instance | 
                   BindingFlags.IgnoreCase)) 
{
  if (info.CanRead && !PropertyNamesToExclude.Contains(info.Name)) 
  {
    string value = info.GetValue(obj, null) != null ? 
                                            info.GetValue(obj, null).ToString() :
                                            null;
    html += "<tr><th>" + info.Name + "</th><td>" + value + "</td></tr>";
  }
}

But of course, this prints out info.Name's like "OrdererGid", when maybe "Orderer Username" would be nicer. Is there anything like this in .NET?

like image 258
Andrew Avatar asked Dec 21 '22 11:12

Andrew


1 Answers

There is a data attribute called DisplayName which allows you to do this. Just annotate your model properties with this and a friendly name for each

[DisplayName("Full name")]
public string FullName { get; set; }
like image 83
Stokedout Avatar answered Jan 13 '23 08:01

Stokedout