如何在此日历视图中的每一天添加复选框?

How to add checkboxes to each day in this calendar view?

我正在尝试向日历视图中的每一天添加一个简单的复选框功能。 It must be inline with the style of the current calendar and when a bool is selected it must be able to save the changes to the database.如有任何建议,我们将不胜感激。

目前我的主要问题是选中的复选框没有保存到数据库中。

Controller.cs

private F2FW _db = new F2FW();

[HttpGet]
    public ActionResult CalendarIndex()
    {
        List<Event> events = new List<Event>();
        Project.Models.Calendar calendar = new Project.Models.Calendar();
        calendar.SetDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        calendar.View(@"~\Views\Patient\Calendar.cshtml");
        calendar.ViewData.Add("events", events);

        ViewBag.calendar = calendar.Render();

        return View(calendar);
    }
        [HttpPost]
        public ActionResult CalendarIndex(User user, CalendarArg calArg, int dayCounter, string[] cbx_day, Patient patient, SessionExercise sessionExercise)
        {
            SessionInformation sessiondata = new SessionInformation();
            Session lastsession = db.Sessions.Where(s => s.ActiveUserID == user.UserID).OrderByDescending(e => e.StartedAt).FirstOrDefault();
            calArg.CompletedToday = DateTime.Today;
            if (ModelState.IsValid)
            {
                if (calArg.CompletionRequested == false)
                {
                    //do nothing!
                }
                else if (calArg.CompletionRequested == true)
                {
                    if (sessiondata.Completed == true)
                    {
                        if (sessionExercise.FinishedAt == calArg.Past)
                        {
                            List<Event> events = new List<Event>();
                            events.Add(new Event() { Title = "Exercises Completed", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Vacation }); //green
                        }

                    }
                    if (sessiondata.Completed == false)
                    {
                        if (sessionExercise.FinishedAt == calArg.Past)
                        {
                            List<Event> events = new List<Event>();
                            events.Add(new Event() { Title = "Exercises Uncompleted", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Critical }); //red
                        }
                    }
                }
                _db.SaveChanges();
                return RedirectToAction("CalendarIndex"); // or where ever you want to go
            }
            else
            {
                return View(calArg);
            }
        }
public class Event
{
    public string Title
    {
        get;
        set;
    }

    public DateTime EventDate
    {
        get;
        set;
    }

    public EventType Type
    {
        get;
        set;
    }

    public enum EventType
    {
        Appointment,
        Meeting,
        Vacation,
        Birthday,
        Personal,
        Critical
    }
}

Model.Calendar.cs

public class Calendar
{
    int _year;
    int _month;
    DateTime _selectedDate;
    string _viewFile = "";
    ViewDataDictionary _viewData = new ViewDataDictionary();

    Func<DateTime, bool, string> _onDayRenderFunc = null;

    public Calendar()
    {
        SetDate(DateTime.Now.Year, DateTime.Now.Month);
    }

    public void SetDate(int year, int month)
    {
        _year = year;
        _month = month;
        _selectedDate = new DateTime(_year, _month, 1);
    }

    public void SetDate(int year, int month, int day)
    {
        _year = year;
        _month = month;
        _selectedDate = new DateTime(_year, _month, day);
    }

    public DateTime Date
    {
        get
        {
            return _selectedDate;
        }
    }

    public void OnDayRender(Func<DateTime, bool, string> func)
    {
        _onDayRenderFunc = func;
    }

    public void View(string viewFile)
    {
        _viewFile = viewFile;
    }

    public ViewDataDictionary ViewData
    {
        get
        {
            return _viewData;
        }
    }

    public string Render()
    {
        string[] dayNames = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

        int daysInMonth = DateTime.DaysInMonth(_year, _month);
        int pYear = _year;
        int pMonth = _month;

        if ((_month - 1) < 1)
        {
            --pYear;
            pMonth = 12;
        }
        else
        {
            --pMonth;
        }

        int daysInPrevMonth = DateTime.DaysInMonth(pYear, pMonth);

        DateTime d1 = new DateTime(_year, _month, 1);
        int dayPos = (int)d1.DayOfWeek;
        daysInPrevMonth -= dayPos - 1;

        StringBuilder control = new StringBuilder();
        control.Append("<table cellpadding=\"0\" cellspacing=\"0\">\n<thead>\n<tr>\n");

        for (int i = 0; i < dayNames.Length; i++)
        {
            control.Append(string.Format("<th>{0}</th>\n", dayNames[i]));
        }

        control.Append("</thead>\n<tbody>\n");

        int totalDaysInMonth = daysInMonth + dayPos;
        int col = 0;
        int day = 0;
        string cellValue = "";

        for (int idx = 0; idx < totalDaysInMonth; idx++)
        {
            if (col == 0)
            {
                control.Append("<tr>\n");
            }

            if (idx >= dayPos)
            {
                ++day;

                if (_viewFile == "")
                {
                    cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, day), true) : day.ToString();
                }
                else
                {
                    ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, day), SelectedDate = _selectedDate, CurrentMonth = true };
                    cellValue = this.Parse(_viewFile);
                }

                control.Append(string.Format("<td data-day=\"{0}\" data-month=\"{1}\" data-year=\"{2}\">{3}</td>\n", day, _month, _year, cellValue));
            }
            else
            {
                if (_viewFile == "")
                {
                    cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(pYear, pMonth, daysInPrevMonth), false) : daysInPrevMonth.ToString();
                }
                else
                {
                    ViewData.Model = new CalendarArg() { Date = new DateTime(pYear, pMonth, daysInPrevMonth), SelectedDate = _selectedDate, CurrentMonth = false };
                    cellValue = this.Parse(_viewFile);
                }

                control.Append(string.Format("<td>{0}</td>\n", cellValue));
                ++daysInPrevMonth;
            }

            if (col == 6)
            {
                control.Append("</tr>\n");
                col = 0;
                continue;
            }
            ++col;
        }

        if (col < 7)
        {
            int nextMonthDay = 1;

            for (int c = col; c < 7; c++)
            {
                if ((_month + 1) > 12)
                {
                    ++_year;
                    _month = 1;
                }
                else
                {
                    ++_month;
                }

                if (_viewFile == "")
                {
                    cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, nextMonthDay), false) : nextMonthDay.ToString();
                }
                else
                {
                    ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, nextMonthDay), SelectedDate = _selectedDate, CurrentMonth = false };
                    cellValue = this.Parse(_viewFile);
                }

                control.Append(string.Format("<td>{0}</td>\n", cellValue));
                ++nextMonthDay;
            }

            control.Append("</tr>\n");
        }
        control.Append("</tbody>\n</table>\n");
        return control.ToString();
    }

    private string Parse(string viewFile)
    {
        using (var sw = new StringWriter())
        {
            ControllerContext ctx = new System.Web.Mvc.ControllerContext();
            ctx.HttpContext = new HttpContextWrapper(HttpContext.Current);

            RazorView view = new RazorView(ctx, viewFile, "", false, null);
            TempDataDictionary tdd = new TempDataDictionary();

            var viewContext = new ViewContext(ctx, view, ViewData, tdd, sw);

            view.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }
}

Model.CalendarArg.cs

public class CalendarArg
{
    public DateTime SelectedDate { get; set; }
    public DateTime Date  { get; set; }
    public bool CurrentMonth  { get; set; }
    public bool CompletionRequested { get; set; }
    public DateTime CompletedToday { get; set; }
}

View.CalendarIndex.cshtml

<style>
    table {
        width: 100%;
        border: 0px;
        border-collapse: collapse;
        border: 1px solid #EEE;
    }

        table thead tr th {
            font-family: Tahoma;
            font-weight: normal;
            color: #666;
        }

        table tbody tr td {
            border: 1px solid #EEE;
            width: 14%;
        }

            table tbody tr td .cell1, .cell2 {
                min-height: 150px;
                height: 100%;
            }

            table tbody tr td .selected_day h2 {
                Color: #FFF;
                background-color: #3498DB;
                text-shadow: none;
            }

            table tbody tr td .cell1 {
                background-color: #FFF;
            }

                table tbody tr td .cell1:hover h2 {
                    box-shadow: 1px 2px 3px #999;
                }

            table tbody tr td .cell2 {
                background-color: #FCFCFC;
            }

                table tbody tr td .cell2 h2 {
                    color: #CCC;
                }

            table tbody tr td h2 {
                font-family: Tahoma;
                font-size: 20px;
                font-weight: normal;
                float: right;
                margin: 0px;
                padding: 6px;
                color: #154B67;
                background-color: #EEE;
                display: block;
                width: 25px;
                height: 25px;
                text-align: center;
                text-shadow: 2px 1px #FFF;
            }

            table tbody tr td .evt {
                font-family: Tahoma;
                font-size: 12px;
                margin: 5px;
                padding: 10px;
                color: #FFF;
                border-radius: 2px;
            }

            table tbody tr td .clear {
                clear: both;
            }

    .Meeting {
        background-color: #DDD;
        color: #222 !important;
    }

    .Personal {
        background-color: #3498DB;
    }

    .Vacation {
        background-color: #2ECC71;
    }

    .Appointment {
        background-color: #F5AB35;
    }

    .Critical {
        background-color: #F22613;
    }
</style>@Html.Raw(ViewBag.calendar)

View.Calendar.cshtml

    @model Project.Models.CalendarArg
    @{
        CalendarArg calArg = this.Model;
        List<Project.Controllers.Event> events = (List<Project.Controllers.Event>)ViewData["events"];


        string cssClass = calArg.CurrentMonth == true ? "cell1" : "cell2";
    }

    @if (calArg.Date.Day == calArg.SelectedDate.Day)
    {
        cssClass += " selected_day";
    }

@if (calArg.Date.Day == calArg.Date.Day)
{
    if (DateTime.Now <= calArg.Date)
    {
        @Html.CheckBoxFor(m => m.CompletionRequested, new { @checked = calArg.CompletionRequested });
    }
}

    <div class="@cssClass">
        <h2>@calArg.Date.Day.ToString()</h2>
        <div class="clear"></div>

            @foreach (var evt in events)
            {
                if (evt.EventDate.Date.ToString("yyyyMMdd") == calArg.Date.ToString("yyyyMMdd"))
                {
                    <div class="evt @evt.Type.ToString()">@evt.Title</div>
                }
            }
        </div>

更新

将这行代码添加到Calendar.cshtl:

@if (calArg.Date.Day == calArg.Date.Day)
{
    @Html.CheckBoxFor(m => m.CompletionRequested, new { @checked = calArg.CompletionRequested }); 
}

它出人意料地有效,所以我想我想知道如何更改 calendar index 中的 css 样式 sheet 以使复选框与日历设计齐平(即与日历内联,而不仅仅是在日历之上)以及如何将对 bool 的更改保存到数据库中。

将其放入 foreach 循环中:

    @Html.CheckBoxFor(m => m.CompletionRequested , new { @checked = evt.CompletionRequested });

更新: 在评论中回答你的问题。对控制器执行 HttpPost 并传递模型数据。

[HttpPost]
public ActionResult CalendarIndex(CalendarArg model)
{
     // Check that model is valid
    if(ModelState.IsValid)
    {
        // CODE here to update Database
        return RedirectToAction("Index"); // or where ever you want to go
    }
    else
    {
        return View(model); // Return back to View, model is not valid
    }
}

更新 2:

如果您想添加一个 class 名称,您可以这样做:

@Html.CheckBoxFor(m => m.CompletionRequested , new { @checked = evt.CompletionRequested, @class = "checkbox" });

或者您可以像这样添加 css:

input[type="radio"]:checked
{
      // css when radio button is selected
}

input[type="radio"]
{
      // css when radio button is not selected
}

这些 CSS 样式是全局样式,因此每个类型为 radio 的输入元素都将获得样式。

而当你想更改数据库上下文时,你需要先从上下文中找到当前的。然后将 true 值添加到 CompletionRequested 属性,然后从您的上下文中调用 SaveChanged 方法。您的第一个问题是在日历视图上获取复选框,而不是如何将更改保存到数据库。那是另一个问题。