简体   繁体   English

ASP.NET MVC中fullcalendar的CRUD操作

[英]CRUD operation on fullcalendar in ASP.NET MVC

I have a problem with fullcalendar and ASP.NET MVC.我对 fullcalendar 和 ASP.NET MVC 有疑问。 I set format date of 'YYYY/MM/DD', but when I try to save event then JS or C# (I am not so sure) change automatically format to 'YYYY/DD/MM'.我将格式日期设置为“YYYY/MM/DD”,但是当我尝试保存事件时,JS 或 C#(我不太确定)会自动将格式更改为“YYYY/DD/MM”。 The result of it is that when I select date where day is equal or greater than 13 then I get exception 'The conversion of datetime2 data type to a datetime data type resulted in an out-of-range value' and always get date like '[0001-01-01]'.结果是,当我 select 日期等于或大于 13 时,我得到异常 '将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围' 并且总是得到像 ' [0001-01-01]'。

I have tried change in View in different ways format of date, but without any possitive result.我尝试以不同的方式更改视图的日期格式,但没有任何积极的结果。

I wanted implement code from this site: http://www.do.netawesome.com/2017/07/curd-operation-on-fullcalendar-in-as.net-mvc.html我想从这个网站实现代码: http://www.do.netawesome.com/2017/07/curd-operation-on-fullcalendar-in-as.net-mvc.html

In my project, but it doesn't work fine with dates.在我的项目中,但它不适用于日期。 But when I downloaded this project from the site and opened then everything was OK and I don't know what is wrong with my project.但是当我从网站下载这个项目并打开时一切正常,我不知道我的项目出了什么问题。

Do You have any ideas?你有什么想法?

I will be grateful for any answer.我将不胜感激任何答案。

My View:我的看法:

@{
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>

My Controller:我的Controller:

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} };
    }
  }
}

Model: Model:

namespace School_Project.Models
{
using System;
using System.Collections.Generic;

public partial class Events
{
    public int EventID { get; set; }
    public int ClassID { get; set; }
    public string Subject { get; set; }
    public string Description { get; set; }
    public System.DateTime Start { get; set; }

    public Nullable<System.DateTime> End { get; set; }
    public string ThemeColor { get; set; }
    public bool IsFullDay { get; set; }

    public virtual School_Class School_Class { get; set; }

  }
}

In the question you said在你说的问题中

"I set format date of 'YYYY/MM/DD'". “我设置了‘YYYY/MM/DD’的格式日期”。

However from the code it's clear that this isn't true.然而,从代码中很明显这不是真的。 In every instance in your example, you output dates in the format DD/MM/YYYY which is potentially ambiguous (there could be confusion over the days and months, as you've found).在您的示例中的每个实例中,您都以DD/MM/YYYY格式输出日期,这可能是不明确的(正如您发现的那样,日期和月份可能会混淆)。 Also the "A" in your format string (to output AM/PM) is meaningless because HH:mm already outputs the time in 24-hr format.此外,格式字符串中的“A”(输出 AM/PM)毫无意义,因为HH:mm已经以 24 小时格式输出时间。 So I'm not surprised the server is getting confused about what date you mean.所以我并不奇怪服务器对你的意思是什么日期感到困惑。

You should use an unambiguous format which the server cannot possibly mis-interpret.您应该使用服务器不可能误解的明确格式。 ISO-8601 format is the commonly accepted standard for this. ISO-8601 格式是普遍接受的标准。 momentJS provides a ready-made method called toISOString() for outputting in that format: momentJS 提供了一个名为toISOString()的现成方法用于以该格式输出:

event.start.toISOString();

See https://momentjs.com/docs/#/displaying/as-iso-string/ for more details.有关更多详细信息,请参阅https://momentjs.com/docs/#/displaying/as-iso-string/

Another thing to note is that your libraries, including momentJS (which deals with dates) are obsolete as per the fullCalendar docs: https://fullcalendar.io/support .另一件需要注意的事情是,根据 fullCalendar 文档,您的库,包括 momentJS(处理日期)已过时: https ://fullcalendar.io/support。 You need jQuery 2 or above, and momentJS 2.9 or above您需要 jQuery 2 或更高版本,以及 momentJS 2.9 或更高版本

Sorry for ambiguous, I have written this post very late.抱歉含糊不清,我写这篇文章很晚。 But I found the solution!但我找到了解决方案!

First of all when I wanted to save my form:首先,当我想保存表单时:

 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();
    }

Then I had some trouble with date format, because C# understood only format like 'MM-DD-YYYY HH:mm', but I wanted display 'DD-MM-YYYY HH:mm'.然后我在日期格式方面遇到了一些麻烦,因为 C# 只理解像“MM-DD-YYYY HH:mm”这样的格式,但我想显示“DD-MM-YYYY HH:mm”。

So I simply changed the position of date elements.所以我只是改变了日期元素的位置。

        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);

Right now everything works as I wanted.现在一切都如我所愿。

i have a suggestion for you:我有一个建议给你:

Go to the file: Web.Config and add this line of code on the 18th line: Go到文件:Web.Config在第18行添加这行代码:

<globalization culture="en-GB" uiCulture="en-GB"/>

this will help you dealing with hours and dates with the component full calendar这将帮助您使用完整日历组件处理时间和日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM