Naweed Akram's Blog
<sharing: Knowledge />
Creating a Date Badge for your Posts in ASP.NET MVC
Posted: August 10, 2010

Ever wanted to create a date badge for your posts in ASP.NET MVC (similar to the one on the side). It is actually very easy to do so.


Let's look at how this can be achieved with the help of simple CSS and a helper extension.


Create a new ASP.NET MVC 2.0 project (or open an existing one). Open the Site.css file in the Content folder and paste in the following CSS code:

/* Date Badge */
    border: 1px solid #999; 
    font-family: Georgia,"Times New Roman", Calibri, serif; 
    left: -4.8em; 
    line-height: 1; 
    top: 0; 
    width: 3.5em;

.entryDate span 
    display: block; 
    text-align: center; 

    text-transform: uppercase; 
    font-size: 0.9em;
    padding-top: 0.3em; 

    font-size: 1.5em; 
    font-weight: bold;

    background-color: #FFCC6D; 
    color: #000; 
    font-size: 1.0em; 
    padding: 0.3em 0; 
    margin-top: 0.3em;

Create a simple HTML Helper Extension as follows:

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

"); _outputScript.AppendLine(); _outputScript.Append("" + CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(_date.Month) + ""); _outputScript.AppendLine(); _outputScript.Append("" + _date.Day + ""); _outputScript.AppendLine(); _outputScript.Append("" + _date.Year + ""); _outputScript.AppendLine(); _outputScript.Append("
"); _outputScript.AppendLine(); return _outputScript.ToString(); }

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

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

 Now reference it in your views as follows:

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


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

And voila, this is what you get:


Happy coding till next time, when we revisit the date badge to create a strongly typed HTML Helper and get rid of manually declaring the CSS style. Till then.....

Post Comment
Showing all comments

No comments posted
RSS Feed

Quick Links