Thursday, July 28, 2011

Formatting Dates in MVC

When you want to display a value in MVC, for instance a date, that needs to be formatted and may even be null, it can result in a lot of code in the view. For example.
<%: benefit.BenefitCancelledDt.HasValue ? benefit.BenefitCancelledDt.Value.ToString(Constants.SHORTDATE_FORMAT) : "" %>
There is a better alternative. By using data annotations we can do this it in a much shorter for.

Add the following annotation to the property on the model.
[DisplayFormat (DataFormatString = "{0:" + Constants.SHORTDATE_FORMAT + "}")]
public DateTime? BenefitCancelledDt { get; set; }
The view can then be rewritten like this.
<%: Html.DisplayFor (x => x.PolicyBenefits[i].BenefitCancelledDt)%>
Note that I used Html.DisplayFor. The formatting annotation is not used by the other methods like Html.DisplayTextFor. Also note that the expression needs to bind directly to the model and not to a intermediate variable like benefit in the inital code.

No comments:

Post a Comment