Part 46 - Accessing model metadata from custom templated helpers

Leave a Comment
we will discuss, accessing model metadata from with in customized display and edit templated helpers

we have customized DateTime editor template to use jQuery calendar. The problem with this template is that, we have hard-coded the date format string to dd/MM/yyyy. So, from this point, any DateTime property that uses this template will format the date using the hard-coded date format string.

We want our DateTime template to be generic. We don't want any hard-coded logic, with-in the DateTime editor template. The DisplayFormat attribute on the HireDate property of the Employee class must be used to determine the display format of the date. 

Let's remove the hard-coded date format string (dd/MM/yyyy) from DateTime.cshtml. 
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : ""new { @class = "date" })

Decorate HireDate property in Employee class, with DisplayFormat attribute as shown below. Also, make sure ApplyFormatInEditMode parameter is set to true, otherwise the formatting will not be applied in Edit mode.
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime? HireDate { get; set; }

Now, change the code in DateTime.cshtml to use the formatted datetime value as show below. Notice that, we are using ViewData.TemplateInfo.FormattedModelValue.
@Html.TextBox("", Model.HasValue ? ViewData.TemplateInfo.FormattedModelValue : ""new { @class = "date" })

To access model metadata in templates, use @ViewData.ModelMetadata. For, example to access the DisplayFormatString, use @ViewData.ModelMetadata.DisplayFormatString. Along the same lines, if you want to know, the name of the containing class(i.e the class that contains the HireDate property) then use @ViewData.ModelMetadata.ContainerType.ToString().


Post a Comment

Note: only a member of this blog may post a comment.