ASP.NET MVC中对fullcalendar的CRUD操作

时间:2017-10-22 22:38:48

标签: javascript c# asp.net asp.net-mvc fullcalendar

我遇到fullcalendar和ASP.NET MVC的问题。 我将格式日期设置为' YYYY / MM / DD',但是当我尝试保存事件时,JS或C#(我不太确定)会自动更改格式为' YYYY / DD / MM&# 39 ;.结果是当我选择日期等于或大于13的日期时,我得到例外'将datetime2数据类型转换为日期时间数据类型导致超出范围的值'总是得到像[0001-01-01]'。

这样的日期

我尝试使用不同的日期格式更改View,但没有任何可能的结果。

我想从这个网站获得实施代码: http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html

在我的项目中,但它与日期无关。但是当我从网站下载这个项目并打开然后一切都很好,我不知道我的项目有什么问题。

你有什么想法吗?

我将不胜感激。

我的观点:

Double

我的控制器:

@{
ViewBag.Title = "Index";
}

@{ 
Layout = null;
}

<h2>Index</h2>
<div id="calender"></div>

<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"><span id="eventTitle"></span></h4>
        </div>
        <div class="modal-body">
            <button id="btnDelete" class="btn btn-default btn-sm pull-right">
                <span class="glyphicon glyphicon-remove"></span> Remove
            </button>
            <button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
                <span class="glyphicon glyphicon-pencil"></span> Edit
            </button>
            <p id="pDetails"></p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>
</div>

<div id="myModalSave" class="modal fade" role="dialog">
 <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Save Event</h4>
        </div>
        <div class="modal-body">
            <form class="col-md-12 form-horizontal">
                <input type="hidden" id="hdEventID" value="0" />
                <div class="form-group">
                    <label>Subject</label>
                    <input type="text" id="txtSubject" class="form-control"/>
                </div>
                <div class="form-group">
                    <label>Start</label>
                    <div class="input-group date" id="dtp1">
                        <input type="text" id="txtStart" class="form-control" />
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar"></span>
                        </span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="checkbox">
                        <label><input type="checkbox" id="chkIsFullDay" checked="checked" />  Is Full Day event</label>
                    </div>
                </div>
                <div class="form-group" id="divEndDate" style="display:none">
                    <label>End</label>
                    <div class="input-group date" id="dtp2">
                        <input type="text" id="txtEnd" class="form-control" />
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar"></span>
                        </span>
                    </div>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="txtDescription" rows="3" class="form-control"></textarea>
                </div>
                <div class="form-group">
                    <label>Theme Color</label>
                    <select id="ddThemeColor" class="form-control">
                        <option value="">Default</option>
                        <option value="red">Red</option>
                        <option value="blue">Blue</option>
                        <option value="black">Black</option>
                        <option value="green">Green</option>
                    </select>
                </div>
                <button type="button" id="btnSave" class="btn btn-success">Save</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </form>
        </div>
    </div>
</div>
</div>

<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />

<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
    $(document).ready(function () {
        var events = [];
        var selectedEvent = null;
        FetchEventAndRenderCalendar();
        function FetchEventAndRenderCalendar() {
            events = [];
            $.ajax({
                type: "GET",
                url: "/home/GetEvents",
                success: function (data) {
                    $.each(data, function (i, v) {
                        events.push({
                            eventID: v.EventID,
                            title: v.Subject,
                            description: v.Description,
                            start: moment(v.Start),
                            end: v.End != null ? moment(v.End) : null,
                            color: v.ThemeColor,
                            allDay: v.IsFullDay
                        });
                    })

                    GenerateCalender(events);
                },
                error: function (error) {
                    alert('failed');
                }
            })
        }

        function GenerateCalender(events) {
            $('#calender').fullCalendar('destroy');
            $('#calender').fullCalendar({
                contentHeight: 400,
                defaultDate: new Date(),
                timeFormat: 'h(:mm)a',
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay,agenda'
                },
                eventLimit: true,
                eventColor: '#378006',
                events: events,
                eventClick: function (calEvent, jsEvent, view) {
                    selectedEvent = calEvent;
                    $('#myModal #eventTitle').text(calEvent.title);
                    var $description = $('<div/>');
                    $description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
                    if (calEvent.end != null) {
                        $description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
                    }
                    $description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
                    $('#myModal #pDetails').empty().html($description);

                    $('#myModal').modal();
                },
                selectable: true,
                select: function (start, end) {
                    selectedEvent = {
                        eventID: 0,
                        title: '',
                        description: '',
                        start: start,
                        end: end,
                        allDay: false,
                        color: ''
                    };
                    openAddEditForm();
                    $('#calendar').fullCalendar('unselect');
                },
                editable: true,
                eventDrop: function (event) {
                    var data = {
                        EventID: event.eventID,
                        Subject: event.title,
                        Start: event.start.format('DD/MM/YYYY HH:mm A'),
                        End: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
                        Description: event.description,
                        ThemeColor: event.color,
                        IsFullDay: event.allDay
                    };
                    SaveEvent(data);
                }
            })
        }

        $('#btnEdit').click(function () {
            //Open modal dialog for edit event
            openAddEditForm();
        })
        $('#btnDelete').click(function () {
            if (selectedEvent != null && confirm('Are you sure?')) {
                $.ajax({
                    type: "POST",
                    url: '/home/DeleteEvent',
                    data: {'eventID': selectedEvent.eventID},
                    success: function (data) {
                        if (data.status) {
                            //Refresh the calender
                            FetchEventAndRenderCalendar();
                            $('#myModal').modal('hide');
                        }
                    },
                    error: function () {
                        alert('Failed');
                    }
                })
            }
        })

        $('#dtp1,#dtp2').datetimepicker({
            format: 'DD/MM/YYYY HH:mm A'
        });

        $('#chkIsFullDay').change(function () {
            if ($(this).is(':checked')) {
                $('#divEndDate').hide();
            }
            else {
                $('#divEndDate').show();
            }
        });

        function openAddEditForm() {
            if (selectedEvent != null) {
                $('#hdEventID').val(selectedEvent.eventID);
                $('#txtSubject').val(selectedEvent.title);
                $('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
                $('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
                $('#chkIsFullDay').change();
                $('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
                $('#txtDescription').val(selectedEvent.description);
                $('#ddThemeColor').val(selectedEvent.color);
            }
            $('#myModal').modal('hide');
            $('#myModalSave').modal();
        }

        $('#btnSave').click(function () {
            //Validation/
            if ($('#txtSubject').val().trim() == "") {
                alert('Subject required');
                return;
            }
            if ($('#txtStart').val().trim() == "") {
                alert('Start date required');
                return;
            }
            if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
                alert('End date required');
                return;
            }
            else {
                var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
                var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
                if (startDate > endDate) {
                    alert('Invalid end date');
                    return;
                }
            }

            var data = {
                EventID: $('#hdEventID').val(),
                Subject: $('#txtSubject').val().trim(),
                Start: $('#txtStart').val().trim(),
                End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
                Description: $('#txtDescription').val(),
                ThemeColor: $('#ddThemeColor').val(),
                IsFullDay: $('#chkIsFullDay').is(':checked')
            }
            SaveEvent(data);
            // call function for submit data to the server 
        })

        function SaveEvent(data) {
            $.ajax({
                type: "POST",
                url: '/home/SaveEvent',
                data: data,
                success: function (data) {
                    if (data.status) {
                        //Refresh the calender
                        FetchEventAndRenderCalendar();
                        $('#myModalSave').modal('hide');
                    }
                },
                error: function () {
                    alert('Failed');
                }
            })
        }
    })
</script>

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCEventCalendar.Controllers
{
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetEvents()
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            dc.Configuration.LazyLoadingEnabled = false;
            var events = dc.Events.ToList();
            return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

    [HttpPost]
    public JsonResult SaveEvent(Event e)
    {
        var status = false;
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            if (e.EventID > 0)
            {
                //Update the event
                var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
                if (v != null)
                {
                    v.Subject = e.Subject;
                    v.Start = e.Start;
                    v.End = e.End;
                    v.Description = e.Description;
                    v.IsFullDay = e.IsFullDay;
                    v.ThemeColor = e.ThemeColor;
                }
            }
            else
            {
                dc.Events.Add(e);
            }

            dc.SaveChanges();
            status = true;

        }
        return new JsonResult { Data = new { status = status } };
    }

    [HttpPost]
    public JsonResult DeleteEvent(int eventID)
    {
        var status = false;
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
            if (v != null)
            {
                dc.Events.Remove(v);
                dc.SaveChanges();
                status = true;
            }
        }
        return new JsonResult { Data = new { status = status} };
    }
  }
}

2 个答案:

答案 0 :(得分:1)

在你提出的问题中

  

“我将格式日期设为'YYYY / MM / DD'”。

然而,从代码中可以清楚地知道这不是真的。在您的示例中的每个实例中,您都以DD/MM/YYYY格式输出可能含糊不清的日期(如您所见,可能会在日期和月份上产生混淆)。格式字符串中的“A”(输出AM / PM)也没有意义,因为HH:mm已经以24小时格式输出时间。所以我对服务器对你的日期感到困惑并不感到惊讶。

您应该使用服务器无法解释的明确格式。 ISO-8601格式是普遍接受的标准。 momentJS提供了一个名为toISOString()的现成方法,用于以这种格式输出:

event.start.toISOString();

有关详细信息,请参阅https://momentjs.com/docs/#/displaying/as-iso-string/

另外需要注意的是,根据fullCalendar文档https://fullcalendar.io/support,您的库(包括momentJS(处理日期))已经过时了。您需要jQuery 2或更高版本,以及momentJS 2.9或更高版本

答案 1 :(得分:0)

抱歉暧昧,我很晚才写这篇文章。但我找到了解决方案!

首先,当我想保存表单时:

 function openAddEditForm() {
        if (selectedEvent != null) {
            $('#hdEventID').val(selectedEvent.eventID);
            $('#txtSubject').val(selectedEvent.title);
            $('#txtStart').val(selectedEvent.start.format('DD-MM-YYYY HH:mm'));
            $('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
            $('#chkIsFullDay').change();
            $('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD-MM-YYYY HH:mm') : '');
            $('#txtDescription').val(selectedEvent.description);
            $('#ddThemeColor').val(selectedEvent.color);
        }


        $('#myModal').modal('hide');
        $('#myModalSave').modal();
    }

然后我在日期格式方面遇到了一些麻烦,因为C#只能理解&#39; MM-DD-YYYY HH:mm&#39;这样的格式,但是我希望显示&#39; DD-MM-YYYY HH:mm& #39;

所以我只是改变了日期元素的位置。

        var format_start = $('#txtStart').val().replace(' ', '-').split('-');
        var nowy_start = format_start[1] + '-' + format_start[0] + '-' + format_start[2] + ' ' + format_start[3];

        var format_end = $('#txtEnd').val().replace(' ', '-').split('-');
        var nowy_end = format_end[1] + '-' + format_end[0] + '-' + format_end[2] + ' ' + format_end[3];

        var data = {
            EventID: $('#hdEventID').val(),
            Subject: $('#txtSubject').val().trim(),
            Start: nowy_start.trim(),
            End: $('#chkIsFullDay').is(':checked') ? null : nowy_end.trim(),
            Description: $('#txtDescription').val(),
            ThemeColor: $('#ddThemeColor').val(),
            IsFullDay: $('#chkIsFullDay').is(':checked'),
            ClassID: $('#ddClassID').val()
        }
        SaveEvent(data);

现在一切都按我想要的方式运作。