What it looks like
Recently while working on a project with Asp.Net MVC 3 there was a need for a small calendar similar to the asp.net calendar control. After some searching I decided that the easiest method to get this done would be to write a Html Helper. Below is the code that seems to work nicely. This works even if the browser does not support javascript. For added functionality you could add an extra parameter to show highlighted dates or extend it to fill a page and add content to the cells.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace AntiYes.Helpers
{
public static class CalendarExtensions
{
public static IHtmlString Calendar(this HtmlHelper helper, DateTime dateToShow)
{
DateTimeFormatInfo cinfo = DateTimeFormatInfo.CurrentInfo;
StringBuilder sb = new StringBuilder();
DateTime date = new DateTime(dateToShow.Year, dateToShow.Month, 1);
int emptyCells = ((int)date.DayOfWeek + 7 - (int)cinfo.FirstDayOfWeek) % 7;
int days = DateTime.DaysInMonth(dateToShow.Year, dateToShow.Month);
sb.Append("<table class='cal'><tr><th colspan='7'>" + cinfo.MonthNames[date.Month - 1] + " " + dateToShow.Year + "</th></tr>");
for (int i = 0; i < ((days + emptyCells) > 35 ? 42 : 35); i++)
{
if (i % 7 == 0)
{
if (i > 0) sb.Append("</tr>");
sb.Append("<tr>");
}
if (i < emptyCells || i >= emptyCells + days)
{
sb.Append("<td class='cal-empty'> </td>");
}
else
{
sb.Append("<td class='cal-day'>" + date.Day + "</td>");
date = date.AddDays(1);
}
}
sb.Append("</tr></table>");
return helper.Raw(sb.ToString());
}
}
} |
How would I call this in the
How would I call this in the view?
Katrina, To use it you could
Katrina,
To use it you could do something like:
<%= Html.Calendar(new DateTime(2012, 4, 1)) %>
-- OR -- (with razor syntax)
@Html.Calendar(new DateTime(2012, 4, 1))
There's more information on the full configuration here http://www.sexyselect.net/blog/post/2011/08/16/Writing-a-Razor-MVC3-HTML...
Excellent work thank
Excellent work thank you.
Most helpful
great piece of code - works
great piece of code - works excellent!!!
Thanks!
Hi, this is great stuff,
Hi,
this is great stuff, thanks for sharing with us. It's help me lot and this link ...
http://www.mindstick.com/Articles/27f15546-f7a7-46d7-b03d-ec58296b20f2/?Calendar%20in%20MVC also helped me in completing my project.
Thanks !!!!
I needs me some support for
I needs me some support for the Klingon calendar, can you fixify this code to be compatible pleeze???
Post new comment