Naweed Akram's Blog
<sharing: Knowledge />
Date Badge - Revisited
Posted: August 12, 2010

In my previous post, we looked at creating a date badge for the posts in ASP.NET MVC (similar to the one on the side). However, it suffered from the issue of explicitly defining CSS styles, plus there was no strongly typed HTML helper to work with the model. 


Create a new ASP.NET MVC 2.0 project (or open an existing one). Add a new class called HelperExtentions and add the following code:

public static string RenderDateBadgeHeader(HttpContextBase _context)
    if (_context.Items.Contains("_dateBadgeHeader"))
        return "";
    _context.Items.Add("_dateBadgeHeader", "DateBadge");

    var _outputScript = new StringBuilder();
    _outputScript.AppendLine("<style type=\"text/css\">");
    _outputScript.AppendLine(".entryDate { border: 1px solid #999; font-family: Georgia,\"Times New Roman\", Calibri, serif; left: -4.8em; line-height: 1; top: 0; width: 3.5em; }");
    _outputScript.AppendLine(".entryDate span { display: block; text-align: center; }");
    _outputScript.AppendLine(".postMonth { text-transform: uppercase; font-size: 0.9em; padding-top: 0.3em; }");
    _outputScript.AppendLine(".postDay { font-size: 1.5em; font-weight: bold; }");
    _outputScript.AppendLine(".postYear { background-color: #FFCC6D; color: #000; font-size: 1.0em; padding: 0.3em 0; margin-top: 0.3em; }");

    return _outputScript.ToString();

public static string DateBadge(this HtmlHelper _helper, object _value)
    var _outputScript = new StringBuilder();

    DateTime _date = (DateTime)_value;


    _outputScript.Append("<div class=\"entryDate\">");
    _outputScript.Append("<span class=\"postMonth\">" + CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(_date.Month) + "</span>");
    _outputScript.Append("<span class=\"postDay\">" + _date.Day + "</span>");
    _outputScript.Append("<span class=\"postYear\">" + _date.Year + "</span>");

    return _outputScript.ToString();

public static string DateBadgeFor<TM, TP>(this HtmlHelper<TM> _helper, Expression<Func<TM, TP>> _expression)
    Func<TM, TP> _methodCall = _expression.Compile();
    TP _value = _methodCall(_helper.ViewData.Model);

    return _helper.DateBadge(_value);

Make sure to reference the following namespaces while creating the HTML Helper Extenstion:

using System.Web.Mvc;
using System.Text;
using System.Globalization;
using System.Linq.Expressions;


Now, you can reference it in you view as follows:


<%= Html.DateBadge(new DateTime(2010, 5, 12)) %>


<%= Html.DateBadge(Model.DOB) %>


<%= Html.DateBadgeFor(_model => _model.DOB) %>

Happing coding.

Post Comment
Showing all comments

No comments posted
RSS Feed

Quick Links