Blog from Saravanan Arumugam

Let us talk about Technologies

Data formatting in HtmlHelper.EditFor


I have a date time filed coming from entity model. When I use @Html.DisplayFor() or @Html.EditFor(), I am getting a long date-time string like “2012-04-05 11:00:40.270”. I wanted to display just the date not the time.

I tried using @Html.EditorFor(model => ((DateTime)model.ShiftDate).ToShortDateString()). It threw me the following runtime exception.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Eventually I figured out that System.ComponentModel.DataAnnotations.DisplayFormatAttribute can help to format the date. If the model is a class you created in your Model folder, we can simply apply the DisplayForatAttribute and get the result.

But to format the Entity’s property, or a service’s DataContract member, we wouldn’t want to apply the attribute directly, since every Service update would refresh what we coded.

The best thing to do is to extend the Entity or DataContract by writing a partial class and add an additional property. Then add the formatting to the property.

Here is what I did to display the formatted “Shift Date” of “Record” class.

public partial class Record
{        
    [DisplayName("Shift Date")]
    [DisplayFormat(DataFormatString="{0:MM/dd/yyyy}", 
        ApplyFormatInEditMode=true)]
    public System.Nullable<System.DateTime> FormattedShiftDate
    {
        get
        {
            return this.ShiftDateField;
        }
        set
        {
            this.ShiftDateField = value;
        }
    }
}

Write a partial class (remember to specify the same namespace as the entity), create an additional Property which internally works with the same original field. In my case, I created FormattedShiftDate, where I used the DisplayNameAttribute to name the property as Shift Date. I have formatted the Property with DisplayFormatAttribute with DataFormatString=”MM/dd/yyyy”.

In the views, instead of using ShiftDate in the helper methods, start using FormattedShiftDate.

@Html.EditorFor(model => model.FormattedShiftDate)
@Html.ValidationMessageFor(model => model.FormattedShiftDate)
Advertisements

One response to “Data formatting in HtmlHelper.EditFor

  1. Sneha February 11, 2015 at 2:04 am

    where to write the partial class.
    thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: