Wednesday, 22 April 2015

Using UIHint - Editor and Display Templates


Constants Used by the Date and Email Example


public partial class UiHintEditorTemplateConstants
    {
        public const string DateCalendar = "DateCalendar";
    }

public partial class UiHintDisplayTemplateConstants
    {
        public const string Date = "Date";
        public const string DateTime = "DateTime";
        public const string Email = "Email"; //Example 2 below
    }

Example 1: Date

Objectives

  • I wanted to hide the default value (1/1/0001 12:00:00 AM) when the date was null
  • I also wanted to format the date as MM/DD/YYYY
Date issue as detailed in this post.

Model

[Display(Name = "Upload From Date")]
            [DataType(DataType.DateTime)]
            [UIHint(UiHintEditorTemplateConstants.DateCalendar)]
            [UIHint(UiHintDisplayTemplateConstants.Date)]
            public String FormUsedFromDate { get; set; } //changed due to data annotations and chrome issue


HTML

Instead of using TextBoxFor, use EditorFor
@Html.EditorFor(x => x.Criteria.FormUsedFromDate, UiHintEditorTemplateConstants.DateCalendar)

This is for displaying the DateTime
@Html.DisplayFor(x => item.EventDateTime, UiHintDisplayTemplateConstants.DateTime)

Editor & Display Template

 Place the editor templates in Views/Shared

DateCalendar Editor Template

@using System.Globalization
 
@model DateTime?
           
@Html.TextBox("", (Model != null && Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001") ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "datePicker", maxlength = "12", size = "12" })

Date Display Template

@using System.Globalization
@model DateTime?
 
@if(Model != null && Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001"))
{
    <text>@Model.Value.ToString("MM/dd/yyyy")</text>
}

DateTime Display Template

@using System.Globalization
@model DateTime?
 
@if(Model != null && Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001"))
{
<text>
    @Model.Value.ToString("MM/dd/yyyy") 
    @Model.Value.ToLongTimeString()
</text>
}

Example 2: Email

We can use this display template when ever we need to display an email and we also need to make it a link.

HTML

@Html.DisplayFor(x => x.User.Email, UiHintDisplayTemplateConstants.Email)

Email Display Template

@using System.Globalization
@model String
 
@if(!String.IsNullOrWhiteSpace(Model) && Model.IsEmail())
{
    <text>
        <a href="mailto:@Model">@Model</a>
    </text>
}