Select Page
This entry has been published on 2016-07-12 and may be out of date.

Last Updated on 2016-07-12.

[:en]Databases like MySQL do not allow any special characters in table column names, so most developers use camelcase or underscores. To make it readable for the end user in your software, you often have to manually type a friendly description.

As there is no way to set a “friendly name” value in the DB table structure directly, you might think of putting some additional data into the .Net database entity  model. This is not always a good idea, because data could get lost when you update your model structure from DB.

So the most useful way I found so far in ASP.Net is to use a combination of System.ComponentModel.DataAnnotations and Model Metadata.

Example

You have a table mytable in your model mymodel, which contains a column mycolumn. The friendly name for mycolumn should be “My Column”.

In your Models folder (Visual Studio Solution Explorer), create 2 class files called MetaData.cs and PartialClasses.cs.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace myproject.Models
{
    public class MetaData
    {
        public class mytableMetaData
        {
            [Display(Name = "My Column")]
            public object mycolumn;
            

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace myproject.Models
{    
    [MetadataType(typeof(MetaData.mytableMetaData))]
    public partial class mytable
    {
    }
}

In your .cshtml file, use:

@Html.DisplayNameFor(m => m.mycolumn)

You should now see the friendly column name “My Column” in your browser.

E.g. “@Html.ValidationSummary()” now also uses the display name from Metadata.

If you refresh your model structure later, these two classes are not affected.

Reference[:]