관리 메뉴

미래 개발 연구소

[ASP.NET MVC][달력 만들기] 3. ASP.NET MVC Model - 일정추가 본문

ASP.NET MVC

[ASP.NET MVC][달력 만들기] 3. ASP.NET MVC Model - 일정추가

쓰봥 2022. 2. 20. 02:16
SMALL

이번에는 지난 시간에 만들어둔 Calender View 에 일정을 추가 해 보도록 하자.

 


 

우선은 이렇게 Calender에 관련된 Model 을 만들어 주자.

그냥 특별할 거 없이 클래스 파일을 하나 추가 해 주면 된다.

 

여기서 달력의 날짜가 월별로 바뀌는 내용에 대해서도 같이 추가 할 예정이다.

우선 달력을 관리하는 내용부터 추가해 보도록 하자.

우선 해당 프로젝트에서는 아래의 그림과 같이

달력의 날짜를 관리해주는 클래스를 하나 만들어서 사용해보자.

 


[CalenderManaged.cs]

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace witWebApp.Calender
{
    public class CalenderManaged
    {
        /// <summary> 오늘 날짜 </summary>
        DateTime _curDate = new DateTime();

        /// <summary> 달력의 시작 날짜 </summary>
        DateTime _beginDate = new DateTime();

        /// <summary> 달력의 마지막 날짜 </summary>
        DateTime _endDate = new DateTime();

        /// <summary> 월의 시작 날짜 </summary>
        DateTime _monthBeginDate = new DateTime();

        /// <summary> 월의 마지막 날짜 </summary>
        DateTime _monthEndDate = new DateTime();

        public DateTime CurrentDate
        {
            set { _curDate = value; }
            get { return _curDate; }
        }

        public DateTime MonthBeginDate
        {
            get { return _monthBeginDate; }
        }

        public DateTime MonthEndDate
        {
            get { return _monthEndDate; }
        }

        /// <summary>
        /// 
        /// </summary>
        private void GetBeginEndDate()
        {
            if (_curDate == new DateTime())
                return;

            int current_year = _curDate.Year;
            int current_month = _curDate.Month;

            _monthBeginDate = new DateTime(current_year, current_month, 1);
            _monthEndDate = new DateTime(current_year, current_month, GetMonthEndDay(current_year, current_month));

            int monthBeginDayOfWeek = GetDayOfWeek(_monthBeginDate);
            int monthEndDayOfWeek = GetDayOfWeek(_monthEndDate);

            if (monthBeginDayOfWeek == 7)
            {
                _beginDate = new DateTime(current_year, current_month, 1);
            }
            else
            {
                _beginDate = GetCalenderBeginDate(_monthBeginDate);
            }

            if (monthEndDayOfWeek == 6)
            {
                _endDate = new DateTime(current_year, current_month, GetMonthEndDay(current_year, current_month));
            }
            else
            {
                _endDate = GetCalenderEndDate(_monthEndDate);
            }



        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        private int GetMonthEndDay(int year, int month)
        {
            return DateTime.DaysInMonth(year, month);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private int GetDayOfWeek(DateTime date)
        {
            DayOfWeek dayOfWeek1 = date.DayOfWeek;
            int dayOfWeek = -1;

            switch (dayOfWeek1)
            {
                case DayOfWeek.Sunday:
                    dayOfWeek = 7;
                    break;
                case DayOfWeek.Monday:
                    dayOfWeek = 1;
                    break;
                case DayOfWeek.Tuesday:
                    dayOfWeek = 2;
                    break;
                case DayOfWeek.Wednesday:
                    dayOfWeek = 3;
                    break;
                case DayOfWeek.Thursday:
                    dayOfWeek = 4;
                    break;
                case DayOfWeek.Friday:
                    dayOfWeek = 5;
                    break;
                case DayOfWeek.Saturday:
                    dayOfWeek = 6;
                    break;
            }

            return dayOfWeek;
        }

        /// <summary>
        /// 
        /// </summary>
        private DateTime GetCalenderBeginDate(DateTime date)
        {
            DateTime calBeginDate = new DateTime();

            DateTime chkDate = date.AddDays(-1);
            int current_dayOfWeek = GetDayOfWeek(chkDate);

            while (true)
            {
                if (current_dayOfWeek == 7)
                {
                    calBeginDate = chkDate;
                    break;
                }

                chkDate = chkDate.AddDays(-1);
                current_dayOfWeek = GetDayOfWeek(chkDate);
            }

            return calBeginDate;
        }

        private DateTime GetCalenderEndDate(DateTime date)
        {
            DateTime calEndDate = new DateTime();

            DateTime chkDate = date.AddDays(1);
            int current_dayOfWeek = GetDayOfWeek(chkDate);

            while (true)
            {
                if (current_dayOfWeek == 6)
                {
                    calEndDate = chkDate;
                    break;
                }

                chkDate = chkDate.AddDays(1);
                current_dayOfWeek = GetDayOfWeek(chkDate);
            }

            return calEndDate;
        }

        /// <summary>
        /// 
        /// </summary>
        public DataTable GetCalender()
        {
            GetBeginEndDate();

            if (_beginDate == new DateTime())
                return null;

            DataTable dtList = new DataTable();
            dtList.Columns.Add("id");
            dtList.Columns.Add("date");
            dtList.Columns.Add("isInMonth");
            dtList.Columns.Add("row");
            dtList.Columns.Add("col");
            dtList.Columns.Add("event");

            string id = string.Empty;

            int row = 1;
            int col = 1;

            int cnt = 0;

            DateTime chkDate = _beginDate;

            while (true)
            {
                if (row > 5 && col > 7)
                    break;

                if (col > 7)
                {
                    row++;
                    col = 1;
                }

                DataRow newRow = dtList.NewRow();

                id = string.Format("r{0}c{1}", row, col);

                bool isInMonth = false;
                if (_curDate.Month != chkDate.Month)
                    isInMonth = false;
                else
                    isInMonth = true;

                newRow["id"] = id;
                newRow["date"] = chkDate.ToString("yyyy-MM-dd");
                newRow["isInMonth"] = isInMonth.ToString();
                newRow["row"] = row;
                newRow["col"] = col;

                dtList.Rows.Add(newRow);

                chkDate = chkDate.AddDays(1);

                col++;
            }


            return dtList;
        }
    }
}

간략하게 설명 하면, 앞에서 구성한 달력은 6x6 으로 구성된 사이즈 이므로,

해당 월의 의 시작 날짜와 달력의 시작 날짜를, 월의 마지막 날과 달력의 마지막 날을 구해서

월별 달력에 들어갈 날짜를 계산하고, 그 결과를 DataTable 에 채워 주는 것이다.

 

조금 헷갈릴거 같아서 약간의 추가 설명을 덧붙이면

예를 들어 2022년 1월의 달력을 그려준다고 가정하고

 

[월의 시작 날짜]       : 2022년 1월 1일

[달력의 시작 날짜]    : 2021년 12월 26일

[월의 마지막 날짜]    : 2022년 1월 31일

[달력의 마지막 날짜] : 2022년 2월 5일

위 날짜를 구하는 내용이고, 이걸 이용해서 달력을 그리는데

1월에 포함된 달과 포함되지 않는 날을 구분 할 수 있다.

 

그리고 이제 이걸 이용해서 View 에 뿌려줄 데이터를 구성해 보자.

 

[CalenderModel.cs]

using System;
using System.Collections.Generic;
using System.Data;

namespace witWebApp.Models
{
    public class CalenderModel
    {
        public int year { get; set; }
        public int month { get; set; }
        public int day { get; set; }


        public Dictionary<string, string> dateDic { get; set; }
        public Dictionary<string, string> dateStyleDic { get; set; }
        public Dictionary<string, string> dateDescDic { get; set; }

        public int weeks { get; set; }
        public string control { get; set; }


        /// <summary>
        /// 
        /// </summary>
        public void SetCalenderData()
        {
            if (this.month == null && this.year == null && this.day == null)
                return;

            this.dateDic = new Dictionary<string, string> { };
            this.dateStyleDic = new Dictionary<string, string> { };
            this.dateDescDic = new Dictionary<string, string> { };

            weeks = -1;

            Calender.CalenderManaged calManager = new Calender.CalenderManaged();
            DateTime date = new DateTime(this.year, this.month, this.day);

            calManager.CurrentDate = date;

            DataTable dtList = calManager.GetCalender();
            if (dtList != null)
            {
                string start_date = calManager.MonthBeginDate.ToString("yyyy-MM-dd");
                string end_date = calManager.MonthEndDate.ToString("yyyy-MM-dd");

                DataTable dtEvent = new DataTable();
                

                int cnt = 1;
                foreach (DataRow row in dtList.Rows)
                {
                    string id = row["id"].ToString();
                    string date_str = row["date"].ToString();
                    bool isInMonth = Boolean.Parse(row["isInMonth"].ToString());
                    string evt = string.Empty;


                    if (dtEvent != null)
                    {
                        evt = "일정 등록";
                    }

                    DateTime cur_date = DateTime.Parse(date_str);

                    string key = id;
                    string style_key = id + "_style";

                    string style = "day";
                    if (isInMonth)
                        style = "day";
                    else
                        style = "day other-month";

                    int row_val = Int32.Parse(row["row"].ToString());
                    cnt = row_val;

                    this.dateDic[id] = cur_date.Day.ToString();
                    this.dateStyleDic[id] = style;
                    this.dateDescDic[id] = evt;
                }

                //Console.WriteLine("weeks : " + cnt);
                weeks = cnt;

            }

        }
    }
}

 

위 내용의 핵심은 이전에 CalenderManager.cs 에서 구한 내용을 

public Dictionary<string, string> dateDic { get; set; }
public Dictionary<string, string> dateStyleDic { get; set; }
public Dictionary<string, string> dateDescDic { get; set; }

Dictionary 에 채워넣고 View 에 전달 하는 것이다.

 

이제 Model 에서 정리한 데이터를 View 에 전달 하는 방법은

Calendercshtml 에 아래의 구문을 추가 해 준다.

 

@using witWebApp.Models
@model CalenderModel;

View 에서 Model 을 호출 할 때 이렇게 선언해 주면

모델에서 넘어온 데이터를 적용 할 수 있다.

 

<li class="@Html.DisplayFor(model => model.dateStyleDic["r1c1"])">
    <div class=date>@Html.DisplayFor(model => model.dateDic["r1c1"])</div>
    @if (Model.dateDescDic["r1c1"].Length > 0)
    {                        
        <div class="event">@Html.DisplayFor(model => model.dateDescDic["r1c1"])</div>
    }
</li>

 

이렇게 @Html.DisplayFor(model => model.dateDic["r1c1"])

구문을 이용해서 데이터를 보여준다.

 

그리고 이번에 월별로 달력을 제어하는 부분은 다음 글에서 자세하게 다뤄 볼 예정이다.

 

다음에 배워 볼 내용의 핵심은 View 단에서 Controller 단에서

실행할 Action 을 제어하는것이 핵심이다.