asp.net MVC 行事曆

ASP.NET MVC

最近早期系統行事曆要都是自己繪製,另有用途,先筆記一下,在MVC專案當中,建立一個CalendarModel

以備不時之需。

    public class CalendarModel
    {
        public string Title { get; set; }

        public int StartDayOfWeak { get; set; }

        public int EndDay { get; set; }
    }

Controller部分

        public IActionResult Index(string year, string month)
        {
            var currentDate = DateTime.Now;
            if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
                currentDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
             


            var date = new DateTime(currentDate.Year, currentDate.Month, 1);

            var model = new CalendarModel
            {
                Title = date.ToString("yyyy MMMM").ToUpper(),
                StartDayOfWeak = (int)date.DayOfWeek,
                EndDay = date.AddMonths(1).AddSeconds(-1).Day
            };

            return View(model);
        }

最後View這一塊

@model WebApplication3.Models.CalendarModel
@{ ViewData["Title"] = "Calendar"; }


<div class="calendar-container">
    <table class="table table-bordered table-sm">
        <thead>
            <tr>
                <th colspan="7" class="text-center">@Model.Title</th>
            </tr>
            <tr>
                <th scope="col">@DayOfWeek.Sunday</th>
                <th scope="col">@DayOfWeek.Monday</th>
                <th scope="col">@DayOfWeek.Tuesday</th>
                <th scope="col">@DayOfWeek.Wednesday</th>
                <th scope="col">@DayOfWeek.Thursday</th>
                <th scope="col">@DayOfWeek.Friday</th>
                <th scope="col">@DayOfWeek.Saturday</th>
            </tr>
        </thead>
        <tbody>
            @{ var weekCount = Math.Ceiling(((double)(Model.EndDay + Model.StartDayOfWeak) / 7));}
            @for (int week = 0, day = 1, position = 0; week < weekCount; week++)
            {
                <tr>
                    @for (var i = 0; i < 7; i++, position++)
                     {
                        if (position < Model.StartDayOfWeak || ((position - Model.StartDayOfWeak) >= Model.EndDay))
                        {
                            <td></td>   
                        }
                        else
                        {
                        <td class="text-center">@(day++)</td>
                        }
                     }
                </tr> 
            }
        </tbody>
    </table>

</div>

元哥的筆記