ASP.NET MVC: Showing dates using DayCalendarPage extension method

DayCalendarIn my events web site I need to show event dates in lists so users can easily see them. I decided to use day calendar view like shown on image on left. As there are more than one view where I need this functionality I wrote HTML extension method that outputs day calendar view based on current date. In this posting I will show you my extension method and show you how to use it.

DayCalendarPage extension method

Here is the extension method that generates day calendar page like shown above.


public static MvcHtmlString DayCalendarPage(this HtmlHelper helper, DateTime date)
{
   
var buffer = new StringBuilder
();
    buffer.Append(
@"<div class=""dayCalendarPage"">"
);

    buffer.Append(
@"    <div class=""title"">"
);
    buffer.Append(date.ToString(
"MMM"
));
    buffer.Append(
@"    </div>"
);

    buffer.Append(
@"    <div class=""day"">"
);
    buffer.Append(date.ToString(
"dd"
));
    buffer.Append(
@"    </div>"
);

    buffer.Append(
@"</div>"
);

   
return MvcHtmlString.Create(buffer.ToString());
}

This method outputs HTML that is made to nice day calendar page using CSS.

CSS

Here is my CSS that makes calendar look nice. It is not very optimal I think but it works.


/* DAY CALENDAR PAGE */ 
.dayCalendarPage
 
{
    
clear:none
;
    
float:left
;
    
text-align:center

    
border:1px solid lightgrey

    
margin-right:10px
;
}

.dayCalendarPage .title
 
{
    
background-color:Red
;
    
color:White
;
    
width:50px
;    
}

.dayCalendarPage .day
 
{
    
font-size:15pt
;
    
font-weight:bold
;
    
padding-top: 5px
;
    
padding-bottom: 5px;
}

Now as you have extension method and styles added to your project it is time to use them.

How to use DayCalendarPage method

Here is the example about how to use DayCalendarPage extension method.


@foreach (var item in Model.Results) { 
    
<tr>
 
       
<td colspan="10">
 
           @Html.DayCalendarPage(item.StartDate)
          
<div>
 
              @Html.ActionLink(item.Title,
"event", new
{ id = item.Id})
             
<br />
 
              @item.Description
          
</div>
 
      
</td>
 
   
</tr> 
}

Now it’s time to see the output.

Result

Here’s my test result. This data is arbitrary and please don’t take dates here seriously.

DayCalendar in action

Feel free to use this code in your projects if you like it.


Leave a Reply

Your email address will not be published. Required fields are marked *