MVC完整日历不显示事件

时间:2022-08-24 22:13:02

I am implementing a calendar and I have encountered some difficulties because I am learning JavaScript alone and I have not mastered yet.

我正在实施一个日历,我遇到了一些困难,因为我正在学习JavaScript,而我还没有掌握。

My problem is this: I can create the event and save it in the database, but the event and the color of it ... do not appear on the calendar ... can someone find out the solution or where is the problem? If possible ... to create events ... being the color of this event always in random color?

我的问题是这样的:我可以创建事件并将其保存在数据库中,但事件及其颜色......不会出现在日历上......有人能找出解决方案或问题出在哪里?如果可能的话...创建事件......这个事件的颜色总是随机颜色?

View

<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> Remover
                </button>
                <button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
                    <span class="glyphicon glyphicon-pencil"></span> Editar
                </button>
                <p id="pDetails"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</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">Salvar Evento</h4>
            </div>
            <div class="modal-body">
                <form class="col-md-12 form-horizontal">
                    <input type="hidden" id="hdID_Reserva" value="0" />
                    <div class="form-group">
                        <label>Cliente</label>
                        <input name="Nome" class="form-control" type="text" placeholder="Introduza o Nome" id="txtCliente">
                        <input type="hidden" id="txtID_Cliente" name="ID_Cliente" />
                    </div>
                    <div class="form-group">
                        <label>Data de Entrada</label>
                        <div class="input-group date" id="dtp1">
                            <input type="text" id="txtDataEntrada" name="DataEntrada" class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Data de Saida</label>
                        <div class="input-group date" id="dtp1">
                            <input type="text" id="txtDataSaida" name="DataSaida" class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Número Quarto</label>

                        @Html.DropDownList("ID_Quarto", null, "Selecione o Quarto", htmlAttributes: new { @class = "form-control" })
                    </div>
                    <div class="form-group">
                        <label>Número Pessoas</label>
                        <input id="txtNumeroPessoas" name="NumeroPessoas" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Número Noites</label>
                        <input id="txtNumeroNoites" name="NumeroNoites" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Preço</label>
                        <input id="txtPreço" name="Preço" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Observações</label>
                        <input id="txtObservaçoes" name="Observaçoes" class="form-control" />
                    </div>
                    <button type="button" id="btnSave" class="btn btn-success">Salvar</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </form>
            </div>
        </div>
    </div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.min.css" rel="stylesheet" />
<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.print.min.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" />
@section Scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="~/AdminLTE/plugins/fullcalendar-3.9.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: "/CalendárioReservas/GetEvents",
                    success: function (data) {
                        $.each(data, function (i, v) {
                            events.push({
                                eventID: v.ID_Reserva,
                                clienteID: v.ID_Cliente,
                                quartoID: v.ID_Quarto,
                                inicio: moment(v.DataEntrada),
                                fim: v.DataSaida != null ? moment(v.DataSaida) : null,
                                noites: v.NumeroNoites,
                                pessoas: v.NumeroPessoas,
                                preço: v.Preço,
                                obs: v.Observaçoes
                            });
                        })

                        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.clienteID);
                        var $quartoID = $('<div/>');
                        $quartoID.append($('<p/>').html('<b>DataEntrada:</b>' + calEvent.inicio.format("DD-MMM-YYYY HH:mm a")));
                        if (calEvent.fim != null) {
                            $quartoID.append($('<p/>').html('<b>DataSaida:</b>' + calEvent.fim.format("DD-MMM-YYYY HH:mm a")));
                        }
                        $quartoID.append($('<p/>').html('<b>ID_Quarto:</b>' + calEvent.quartoID));
                        $('#myModal #pDetails').empty().html($quartoID);

                        $('#myModal').modal();
                    },
                    selectable: true,
                    select: function (inicio, fim) {
                        selectedEvent = {
                            eventID: 0,
                            clienteID: '',
                            quartoID: '',
                            inicio: inicio,
                            fim: fim,
                            pessoas: '',
                            noites: '',
                            preço: '',
                            obs: ''
                        };
                        openAddEditForm();
                        $('#calendar').fullCalendar('unselect');
                    },
                    editable: true,
                    eventDrop: function (event) {
                        var data = {
                            ID_Reserva: event.eventID,
                            ID_Cliente: event.clienteID,
                            DataEntrada: event.inicio.format('DD/MM/YYYY HH:mm A'),
                            DataSaida: event.fim != null ? event.fim.format('DD/MM/YYYY HH:mm A') : null,
                            ID_Quarto: event.quartoID,
                            NumeroNoites: event.noites,
                            NumeroPessoas: event.pessoas,
                            Preço: event.preço,
                            Observaçoes: event.obs
                        };
                        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: '/CalendárioReservas/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'
            });

            //$('#chkDiaTodo').change(function () {
            //    if ($(this).is(':checked')) {
            //        $('#divDataFim').hide();
            //    }
            //    else {
            //        $('#divDataFim').show();
            //    }
            //});

            function openAddEditForm() {
                if (selectedEvent != null) {
                    $('#hdID_Reserva').val(selectedEvent.eventID);
                    $('#txtID_Cliente').val(selectedEvent.clienteID);
                    $('#txtDataEntrada').val(selectedEvent.inicio.format('DD/MM/YYYY HH:mm A'));
                    //$('#chkDiaTodo').prop("checked", selectedEvent.allDay || false);
                    //$('#chkDiaTodo').change();
                    $('#txtDataSaida').val(selectedEvent.fim != null ? selectedEvent.fim.format('DD/MM/YYYY HH:mm A') : '');
                    $('#ID_Quarto').val(selectedEvent.quartoID);
                    $('#txtNumeroNoites').val(selectedEvent.noites);
                    $('#txtNumeroPessoas').val(selectedEvent.pessoas);
                    $('#txtPreço').val(selectedEvent.preço);
                    $('#txtObservaçoes').val(selectedEvent.obs);
                }
                $('#myModal').modal('hide');
                $('#myModalSave').modal();
            }

            $('#btnSave').click(function () {
                //Validation/
                if ($('#txtID_Cliente').val().trim() == "") {
                    alert('Introduza um Título');
                    return;
                }
                if ($('#txtDataEntrada').val().trim() == "") {
                    alert('Introduza uma Data de Início');
                    return;
                }
                //if ($('#chkDiaTodo').is(':checked') == false && $('#txtDataFim').val().trim() == "") {
                //    alert('Introduza uma Data de Fim');
                //    return;
                //}
                else {
                    var startDate = moment($('#txtDataEntrada').val(), "DD/MM/YYYY HH:mm A").toDate();
                    var endDate = moment($('#txtDataSaida').val(), "DD/MM/YYYY HH:mm A").toDate();
                    if (startDate > endDate) {
                        alert('Data de Fim Inválida');
                        return;
                    }
                }

                var data = {
                    ID_Reserva: $('#hdID_Reserva').val(),
                    ID_Cliente: $('#txtID_Cliente').val().trim(),
                    DataEntrada: $('#txtDataEntrada').val().trim(),
                    DataSaida: $('#txtDataSaida').val().trim(),
                    ID_Quarto: $('#ID_Quarto').val(),
                    NumeroPessoas: $('#txtNumeroPessoas').val(),
                    NumeroNoites: $('#txtNumeroNoites').val(),
                    Preço: $('#txtPreço').val(),
                    Observaçoes: $('#txtObservaçoes').val()
                }
                SaveEvent(data);
                // call function for submit data to the server
            })

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

controller

namespace WebApplication.Controllers
{

    public class CalendárioReservasController : Controller
    {
        private HotelEntities db = new HotelEntities();
        // GET: CalendárioReservas
        public ActionResult Index()
        {
            ViewBag.ID_Quarto = new SelectList(db.Quarto, "ID_Quarto", "ID_Quarto");
            return View();
        }

        public JsonResult GetEvents()
        {
            try
            {
                var events = db.Reserva.Select(p => new
                {
                    ID_Reserva = p.ID_Reserva,
                    ID_Cliente = p.ID_Cliente,
                    ID_Quarto = p.ID_Quarto,
                    DataEntrada = p.DataEntrada,
                    DataSaida = p.DataSaida,
                    NumeroNoites = p.NumeroNoites,
                    NumeroPessoas = p.NumeroPessoas,
                    Preço = p.Preço,
                    Observaçoes = p.Observaçoes

                }).ToList();

                return Json(events, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(ex.Message);
            }
        }

        [HttpPost]
        public JsonResult SaveEvent(Reserva e)
        {
            var status = false;
            using (HotelEntities dc = new HotelEntities())
            {
                if (e.ID_Reserva > 0)
                {
                    //Update the event
                    var v = dc.Reserva.Where(a => a.ID_Reserva == e.ID_Reserva).FirstOrDefault();
                    if (v != null)
                    {
                        v.ID_Cliente = e.ID_Cliente;
                        v.DataEntrada = e.DataEntrada;
                        v.DataSaida = e.DataSaida;
                        v.ID_Quarto = e.ID_Quarto;
                        v.NumeroPessoas = e.NumeroPessoas;
                        v.NumeroNoites = e.NumeroNoites;
                        v.Preço = e.Preço;
                        v.Observaçoes = e.Observaçoes;
                    }
                }
                else
                {
                    dc.Reserva.Add(e);
                }

                dc.SaveChanges();
                status = true;

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

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

Model

public partial class Reserva
    {
        public int ID_Reserva { get; set; }
        public int ID_Cliente { get; set; }
        public int ID_Quarto { get; set; }
        public System.DateTime DataEntrada { get; set; }
        public Nullable<System.DateTime> DataSaida { get; set; }
        public int NumeroPessoas { get; set; }
        public Nullable<int> NumeroNoites { get; set; }
        public Nullable<decimal> Preço { get; set; }
        public string Observaçoes { get; set; }

        public virtual Cliente Cliente { get; set; }
        public virtual Quarto Quarto { get; set; }
    }

1 个解决方案

#1


0  

Your event objects do not conform to the specification laid out at https://fullcalendar.io/docs/event-object .

您的事件对象不符合https://fullcalendar.io/docs/event-object中规定的规范。

Here is the problem:

这是问题所在:

$.each(data, function (i, v) {
  events.push({
    eventID: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    inicio: moment(v.DataEntrada),
    fim: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

FullCalendar doesn't speak Portuguese. The event property names have to match the ones in the documentation otherwise it will ignore them. It doesn't magically know that inicio means start, for example. This means it cannot read any start time from your event, and therefore it doesn't know how to display it on the calendar.

FullCalendar不会说葡萄牙语。事件属性名称必须与文档中的属性名称匹配,否则将忽略它们。例如,它并不神奇地知道inicio意味着开始。这意味着它无法从您的活动中读取任何开始时间,因此它不知道如何在日历上显示它。

Again as per the documentation, your events are also required to have a title, which you didn't appear to include at all.

再次根据文档,您的活动也需要有一个标题,您似乎根本没有包括。

Try this instead:

试试这个:

$.each(data, function (i, v) {
  events.push({
    id: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    title: '[You need to choose something to put here]',
    start: moment(v.DataEntrada),
    end: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

I have just changed the properties which matter for displaying the event. For other custom properties, you can call them anything you like, but the ones which have a defined purpose in fullCalendar must be named correctly.

我刚刚更改了显示事件的重要属性。对于其他自定义属性,您可以将它们称为任何您喜欢的属性,但必须正确命名在fullCalendar中具有已定义目的的属性。

P.S. You may need to change the code in your eventDrop function in a similar way.

附:您可能需要以类似的方式更改eventDrop函数中的代码。

#1


0  

Your event objects do not conform to the specification laid out at https://fullcalendar.io/docs/event-object .

您的事件对象不符合https://fullcalendar.io/docs/event-object中规定的规范。

Here is the problem:

这是问题所在:

$.each(data, function (i, v) {
  events.push({
    eventID: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    inicio: moment(v.DataEntrada),
    fim: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

FullCalendar doesn't speak Portuguese. The event property names have to match the ones in the documentation otherwise it will ignore them. It doesn't magically know that inicio means start, for example. This means it cannot read any start time from your event, and therefore it doesn't know how to display it on the calendar.

FullCalendar不会说葡萄牙语。事件属性名称必须与文档中的属性名称匹配,否则将忽略它们。例如,它并不神奇地知道inicio意味着开始。这意味着它无法从您的活动中读取任何开始时间,因此它不知道如何在日历上显示它。

Again as per the documentation, your events are also required to have a title, which you didn't appear to include at all.

再次根据文档,您的活动也需要有一个标题,您似乎根本没有包括。

Try this instead:

试试这个:

$.each(data, function (i, v) {
  events.push({
    id: v.ID_Reserva,
    clienteID: v.ID_Cliente,
    quartoID: v.ID_Quarto,
    title: '[You need to choose something to put here]',
    start: moment(v.DataEntrada),
    end: v.DataSaida != null ? moment(v.DataSaida) : null,
    noites: v.NumeroNoites,
    pessoas: v.NumeroPessoas,
    preço: v.Preço,
    obs: v.Observaçoes
  });
});

I have just changed the properties which matter for displaying the event. For other custom properties, you can call them anything you like, but the ones which have a defined purpose in fullCalendar must be named correctly.

我刚刚更改了显示事件的重要属性。对于其他自定义属性,您可以将它们称为任何您喜欢的属性,但必须正确命名在fullCalendar中具有已定义目的的属性。

P.S. You may need to change the code in your eventDrop function in a similar way.

附:您可能需要以类似的方式更改eventDrop函数中的代码。