问题描述
我正在尝试使用 fullcalendar 模块来查看各种事件。到目前为止,只有数据库中的事件会填充到完整日历中,但任何编辑、删除或添加操作都不会反映在数据库中
我使用过masterpage,这个页面是contentpage 所以母版页有样式表和 javascript 文件,例如
<title>ASP.NET FullCalendar</title>
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css" rel="stylesheet" />
..
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js"></script>
<script src="scripts/calendarscript.js" type="text/javascript"></script>
我的 aspx 文件:EventManagement.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="calendar">
</div>
<div id="updatedialog" style="font: 70% 'Trebuchet MS',sans-serif; margin: 50px;display: none;"
title="Update or Delete Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="eventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="eventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="eventStart"></span></td>
</tr>
<tr>
<td class="alignRight">
End: </td>
<td class="alignLeft">
<span id="eventEnd"></span><input type="hidden" id="eventId" /></td>
</tr>
<tr>
<td>
<div class="ui-dialog-buttonset">
<asp:Button ID="Button1" runat="server" Text="Update" ></asp:Button>
<asp:Button ID="Button2" runat="server" Text="delete" ></asp:Button>
</div>
</td>
</tr>
</table>
</div>
<div id="addDialog" style="font: 70% 'Trebuchet MS',sans-serif; margin: 50px;" title="Add Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="addEventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="addEventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="addEventStartDate" ></span></td>
</tr>
<tr>
<td class="alignRight">
End:</td>
<td class="alignLeft">
<span id="addEventEndDate" ></span></td>
</tr>
</table>
</div>
<div runat="server" id="jsonDiv" />
<input type="hidden" id="hdClient" runat="server" />
我的代码隐藏文件:EventManagement.aspx.cs
public partial class EventManagement : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
}
//this method only updates the title and description
//this is called when an event is clicked on the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEvent(CalendarEvent cevent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(cevent.id))
{
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
EventDAO.updateEvent(cevent.id,cevent.name,cevent.description);
return "updated event with id:" + cevent.id + " update title to: " + cevent.name +
" update description to: " + cevent.description;
}
}
return "unable to update event with id:" + cevent.id + " title : " + cevent.name +
" description : " + cevent.description;
}
//this method only updates start and end time
//this is called when a event is dragged or resized in the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEventTime(ImproperCalendarEvent improperEvent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(improperEvent.id))
{
EventDAO.updateEventTime(improperEvent.id,improperEvent.title,improperEvent.description,Convert.ToDateTime(improperEvent.start),Convert.ToDateTime(improperEvent.end),improperEvent.allDay); //allDay parameter added for FullCalendar 2.x
return "updated event with id:" + improperEvent.id + " update start to: " + improperEvent.start +
" update end to: " + improperEvent.end;
}
return "unable to update event with id: " + improperEvent.id;
}
//called when delete button is pressed
[System.Web.Services.WebMethod(true)]
public static String deleteEvent(int id)
{
//idList is stored in Session by JsonResponse.ashx for security reasons
//whenever any event is update or deleted,the event id is checked
//whether it is present in the idList,if it is not present in the idList
//then it may be a malicIoUs user trying to delete someone elses events
//thus this checking prevents misuse
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(id))
{
EventDAO.deleteEvent(id);
return "deleted event with id:" + id;
}
return "unable to delete event with id: " + id;
}
//called when Add button is clicked
//this is called when a mouse is clicked on open space of any day or dragged
//over mutliple days
[System.Web.Services.WebMethod(true)]
public static int addEvent(ImproperCalendarEvent improperEvent)
{
CalendarEvent cevent = new CalendarEvent()
{
name = improperEvent.title,description = improperEvent.description,start = Convert.ToDateTime(improperEvent.start),end = Convert.ToDateTime(improperEvent.end),allDay = improperEvent.allDay
};
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
int key = EventDAO.addEvent(cevent);
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null)
{
idList.Add(key);
}
return key; //return the primary key of the added cevent object
}
return -1; //return a negative number just to signify nothing has been added
}
private static bool CheckAlphaNumeric(string str)
{
return Regex.IsMatch(str,@"^[a-zA-Z0-9 ]*$");
}
}
我的 JsonResponse.ashx 文件
public class JsonResponse : IHttpHandler,IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
DateTime start = Convert.ToDateTime(context.Request.QueryString["start"]);
DateTime end = Convert.ToDateTime(context.Request.QueryString["end"]);
List<int> idList = new List<int>();
List<ImproperCalendarEvent> tasksList = new List<ImproperCalendarEvent>();
//Generate JSON serializable events
foreach (CalendarEvent cevent in EventDAO.getEvents(start,end))
{
tasksList.Add(new ImproperCalendarEvent {
id = cevent.id,title = cevent.name,start = String.Format("{0:s}",cevent.start),end = String.Format("{0:s}",cevent.end),description = cevent.description,allDay = cevent.allDay,});
idList.Add(cevent.id);
}
context.Session["idList"] = idList;
//Serialize events to string
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(tasksList);
//Write JSON to response object
context.Response.Write(sJSON);
}
public bool IsReusable {
get { return false; }
}
}
CalendarEvent.cs 类,它具有关于事件的所有属性
public class CalendarEvent
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public bool allDay { get; set; }
}
我的数据访问类-EventDAO.cs 与数据库对话
public class EventDAO
{
//change the connection string as per your database connection.
//string connectionString = ConfigurationManager.AppSettings["DBConnString"];
private static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
//this method retrieves all events within range start-end
public static List<CalendarEvent> getEvents(DateTime start,DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
sqlConnection con = new sqlConnection(connectionString);
sqlCommand cmd = new sqlCommand("SELECT id,name,description,eventstart,eventend,isFullDay,IsHalfDay,IsQuatDay FROM Events where eventstart between @start AND @end or eventend between @start and @end",con);
cmd.Parameters.AddWithValue("@start",start);
cmd.Parameters.AddWithValue("@end",end);
//cmd.Parameters.Add("@start",sqlDbType.DateTime).Value = start;
//cmd.Parameters.Add("@end",sqlDbType.DateTime).Value = end;
using (con)
{
con.open();
sqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
events.Add(new CalendarEvent() {
id = Convert.ToInt32(reader["id"]),name = Convert.ToString(reader["name"]),description = Convert.ToString(reader["description"]),start = Convert.ToDateTime(reader["eventstart"]),end = Convert.ToDateTime(reader["eventend"]),allDay = Convert.ToBoolean(reader["isFullDay"])
});
}
}
return events;
//side note: if you want to show events only related to particular users,//if user id of that user is stored in session as Session["userid"]
//the event table also contains an extra field named 'user_id' to mark the event for that particular user
//then you can modify the sql as:
//SELECT event_id,title,event_start,event_end FROM event where user_id=@user_id AND event_start>=@start AND event_end<=@end
//then add paramter as:cmd.Parameters.AddWithValue("@user_id",HttpContext.Current.Session["userid"]);
}
//this method updates the event title and description
public static void updateEvent(int id,String title,String description)
{
sqlConnection con = new sqlConnection(connectionString);
sqlCommand cmd = new sqlCommand("UPDATE Events SET name=@title,description=@description WHERE id=@event_id",con);
cmd.Parameters.Add("@title",sqlDbType.VarChar).Value = title;
cmd.Parameters.Add("@description",sqlDbType.VarChar).Value= description;
cmd.Parameters.Add("@event_id",sqlDbType.Int).Value = id;
using (con)
{
con.open();
cmd.ExecuteNonQuery();
}
}
//this method updates the event start and end time ... allDay parameter added for FullCalendar 2.x
public static void updateEventTime(int id,string title,string description,DateTime start,DateTime end,bool allDay)
{
sqlConnection con = new sqlConnection(connectionString);
sqlCommand cmd = new sqlCommand("UPDATE Events SET name=@title,description=@description,eventstart=@event_start,eventend=@event_end,isFullDay=@all_day WHERE id=@event_id",con);
cmd.Parameters.Add("@event_start",sqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@event_end",sqlDbType.DateTime).Value = end;
cmd.Parameters.Add("@event_id",sqlDbType.Int).Value = id;
cmd.Parameters.Add("@all_day",sqlDbType.Bit).Value = allDay;
cmd.Parameters.AddWithValue("@title",title);
cmd.Parameters.AddWithValue("@description",description);
using (con)
{
con.open();
cmd.ExecuteNonQuery();
}
}
//this method deletes event with the id passed in.
public static void deleteEvent(int id)
{
sqlConnection con = new sqlConnection(connectionString);
sqlCommand cmd = new sqlCommand("DELETE FROM Events WHERE (id = @event_id)",con);
cmd.Parameters.Add("@event_id",sqlDbType.Int).Value = id;
using (con)
{
con.open();
cmd.ExecuteNonQuery();
}
}
//this method adds events to the database
public static int addEvent(CalendarEvent cevent)
{
//add event to the database and return the primary key of the added event row
//insert
sqlConnection con = new sqlConnection(connectionString);
sqlCommand cmd = new sqlCommand("INSERT INTO Events(name,isFullDay) VALUES(@title,@description,@event_start,@event_end,@all_day)",sqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("@description",sqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("@event_start",sqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("@event_end",sqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("@all_day",sqlDbType.Bit).Value = cevent.allDay;
int key = 0;
using (con)
{
con.open();
cmd.ExecuteNonQuery();
//get primary key of inserted row
cmd = new sqlCommand("SELECT max(id) FROM Events where name=@title AND description=@description AND eventstart=@event_start AND eventend=@event_end AND isFullDay=@all_day",con);
cmd.Parameters.Add("@title",sqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("@description",sqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("@event_start",sqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("@event_end",sqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("@all_day",sqlDbType.Bit).Value = cevent.allDay;
key = (int)cmd.ExecuteScalar();
}
return key;
}
}
在 javascript 和 asp.net 之间使用的另一个类
ImproperCalendarEvent.cs
public class ImproperCalendarEvent
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
public bool allDay { get; set; }
}
javascript 文件代码 -calendarscript.js
var currentUpdateEvent;
var addStartDate;
var addEndDate;
var globalAllDay;
function updateEvent(event,element) {
alert(event.description);
if ($(this).data("qtip")) $(this).qtip("destroy");
currentUpdateEvent = event;
$('#updatedialog').dialog('open');
$("#eventName").val(event.title);
$("#eventDesc").val(event.description);
$("#eventId").val(event.id);
$("#eventStart").text("" + event.start.toLocaleString());
if (event.end === null) {
$("#eventEnd").text("");
}
else {
$("#eventEnd").text("" + event.end.toLocaleString());
}
return false;
}
function updateSuccess(updateResult) {
alert(updateResult);
}
function deleteSuccess(deleteResult) {
alert(deleteResult);
}
function addSuccess(addResult) {
// if addresult is -1,means event was not added
// alert("added key: " + addResult);
if (addResult != -1) {
$('#calendar').fullCalendar('renderEvent',{
title: $("#addEventName").val(),start: addStartDate,end: addEndDate,id: addResult,description: $("#addEventDesc").val(),allDay: globalAllDay
},true // make the event "stick"
);
$('#calendar').fullCalendar('unselect');
}
}
function UpdateTimeSuccess(updateResult) {
alert(updateResult);
}
function selectDate(start,end,allDay) {
$('#addDialog').dialog('open');
$("#addEventStartDate").text("" + start.toLocaleString());
$("#addEventEndDate").text("" + end.toLocaleString());
addStartDate = start;
addEndDate = end;
globalAllDay = allDay;
//alert(allDay);
}
function updateEventOnDropResize(event,allDay) {
//alert("allday: " + allDay);
var eventToUpdate = {
id: event.id,start: event.start
};
if (event.end === null) {
eventToUpdate.end = eventToUpdate.start;
}
else {
eventToUpdate.end = event.end;
}
var endDate;
if (!event.allDay) {
endDate = new Date(eventToUpdate.end + 60 * 60000);
endDate = endDate.toJSON();
}
else {
endDate = eventToUpdate.end.toJSON();
}
eventToUpdate.start = eventToUpdate.start.toJSON();
eventToUpdate.end = eventToUpdate.end.toJSON(); //endDate;
eventToUpdate.allDay = event.allDay;
PageMethods.UpdateEventTime(eventToUpdate,UpdateTimeSuccess);
}
function eventDropped(event,dayDelta,minuteDelta,allDay,revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function eventResized(event,revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function checkForSpecialChars(stringtocheck) {
//var pattern = /[^A-Za-z0-9 ]/;
//return pattern.test(stringtocheck);
return true;
}
function isAllDay(startDate,endDate) {
var allDay;
if (startDate.format("HH:mm:ss") == "00:00:00" && endDate.format("HH:mm:ss") == "00:00:00") {
allDay = true;
globalAllDay = true;
}
else {
allDay = false;
globalAllDay = false;
}
return allDay;
}
function qTipText(start,description) {
var text;
if (end !== null)
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong> " + end.format("MM/DD/YYYY hh:mm T") + "<br/><br/>" + description;
else
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong><br/><br/>" + description;
return text;
}
$(document).ready(function () {
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,width: 470,buttons: {
"update": function () {
alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,name: $("#eventName").val(),description: $("#eventDesc").val()
};
PageMethods.UpdateEvent(eventToUpdate,updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
$('#calendar').fullCalendar('updateEvent',currentUpdateEvent);
},"delete": function () {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(),deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents',$("#eventId").val());
}
}
}
});
//add dialog
$('#addDialog').dialog({
autoOpen: false,buttons: {
"Add": function () {
//alert("sent:" + addStartDate.format("dd-MM-yyyy hh:mm:ss tt") + "==" + addStartDate.toLocaleString());
var eventToAdd = {
title: $("#addEventName").val(),start: addStartDate.toJSON(),end: addEndDate.toJSON(),allDay: isAllDay(addStartDate,addEndDate)
};
if (checkForSpecialChars(eventToAdd.title) || checkForSpecialChars(eventToAdd.description)) {
alert("please enter characters: A to Z,a to z,0 to 9,spaces");
}
else {
//alert("sending " + eventToAdd.title);
PageMethods.addEvent(eventToAdd,addSuccess);
$(this).dialog("close");
}
}
}
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var options = {
weekday: "long",year: "numeric",month: "short",day: "numeric",hour: "2-digit",minute: "2-digit"
};
$('#calendar').fullCalendar({
theme: true,header: {
left: 'prev,next today customBtn',center: 'title',right: 'month,agendaWeek,agendaDay'
},customButtons: {
customBtn: {
text: 'Custom Button',click: function () {
alert('This custom button is hot! ?\nNow go have fun!');
}
}
},defaultview: 'agendaWeek',eventClick: updateEvent,selectable: true,selectHelper: true,select: selectDate,editable: true,events: "JsonResponse.ashx",eventDrop: eventDropped,eventResize: eventResized,eventRender: function (event,element) {
//alert(event.title);
element.qtip({
content: {
text: qTipText(event.start,event.end,event.description),title: '<strong>' + event.title + '</strong>'
},position: {
my: 'bottom left',at: 'top right'
},style: { classes: 'qtip-shadow qtip-rounded' }
});
}
});
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)