jqgrid edit call ajax every time - asp.net

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si รจ verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid

You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

Related

How to send custom parameter for fetching data using datatables with server side paggination

I am using datatables for fetcing the data from the controller but the issue is that i have to pass some additional parameter for getting the record from the db but the issue is that when i use the sAjaxSource in the datatable request it automatically send all the parameter with the requst like pagination size , columns and sorting and other details without even mentioning it anywhere but when i use the explict ajax request like this.
ajax: {
type: "POST",
data: {accountID : "45d4f5d4f5d"}
}
it only send this parameter which is mentioned in the data and doesn't send other parameter which get sent by default when the request is made using sAjaxSource.
when i send the request like this it works:
$(function () {
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
public ActionResult VoicemailList(JqueryDatatableRequestModel model,string accountId)
{
var totalRecords = 0;
var voicemails = voicemailService.GetVoicemailsListByAccountId(accountId, name: model.sSearch, totalCount: out totalRecords, recordStart: model.iDisplayStart, pageSize: model.iDisplayLength);
var finalResults = Mapper.Map<List<VoicemailModel>>(Voicemails);
return Json(new
{
model.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecords,
aaData = finalResults
}, JsonRequestBehavior.AllowGet);
}`
but when i try to add the additonal parameter it doesnt work
$(function () {
var table = $('#Voicemailtable').DataTable();
var sEcho = table.settings()[0].oAjaxData.sEcho;
var sSearch = table.search();
var iDisplayLength = table.page.len();
var iDisplayStart = table.page.info().start;
var iSortCol_0 = table.order()[0][0];
var sSortDir_0 = table.order()[0][1];
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
ajax: {
url: '#Url.Action("VoicemailList", "Voicemail")',
type: "Get",
data: {
accountId: "45454-df454-f4d65f4d54f"
sEcho: sEcho,
sSearch: sSearch,
iDisplayLength: iDisplayLength,
iDisplayStart: iDisplayStart,
iSortCol_0: iSortCol_0,
sSortDir_0: sSortDir_0
},
},
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
I tried making request from different pattern but its not working if someone could guide my it would be really appriciated.

Ajax and error cannot read properties of undefined

So I am trying to get some data from a table using ajax but this error keeps popping up and I know its related to parameters but I have none of the parameters it says are wrong anyone got any ideas?
I am working in asp.net 6 and am trying to get the data to a controller.
I am currently working in C# and ajax
(function () {
"use strict"
window.onload = function () {
//Reference the DropDownList.
var ddlYears = document.getElementById("ddlYears");
//Determine the Current Year.
var currentYear = (new Date()).getFullYear() + 10;
var less = (new Date()).getFullYear() - 10;
//Loop and add the Year values to DropDownList.
for (var i = less; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
ddlYears.appendChild(option);
}
};
var ScopeTable;
$(document).ready(function () {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
},
{
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
}
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
}
});
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
$("#spnrSave").hide();
});
function btnAddEditScope_click() {
console.log("button clicked")
$.ajax({
url: "Scope/AddEditScope",
type: "GET",
success: function () {
$("#vw_AddEditScope").modal("show");
}
});
}
}());
Error that is being posted
Figured it out just had do adjust my ajax and it worked fine. The tutorial I found is here https://datatables.net/examples/api/multi_filter.html
var ScopeTable;
$(document).ready(function (e) {
ScopeTable = $("#tblScopeView").DataTable({
dom: "Bfrtip",
paging: true,
pagingType: "full_numbers",
buttons: [
"csvHtml5"
],
columns: [
{ data: 'WBS' },
{ data: 'Title' },
{ data: 'Rev' },
{ data: 'ScopeStatus' },
{ data: 'BCP' },
{ data: 'BCPApprovalDate' },
{ data: 'Manager' },
{ data: 'ProjectControlManager' },
{ data: 'ProjectControlEngineer' },
{
mRender: function (data, type, row) {
return "<i class='fa fa-edit btnAddEditScope'></i><span> Edit</span >"
},
class: "btnAddEditScope table-button",
orderable: false
}, {
mRender: function (data, type, row) {
return "<i class='fa fa-trash btnDeleteRow'></i><span> Delete</span >"
},
orderable: false,
class: "table-button"
},
],
createdRow: function (row, data, index) {
$(row).attr("data-id", data.WBSNumber);
$(row).attr("data-month", data.FiscalMonth);
$(row).attr("data-year", data.FiscalYear);
},
error: function (e) {
console.log(e);
}
});
$('#tblScopeView tfoot th').each(function () {
var title = $("#tblScopeView").eq($(this).index()).text();
$(this).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
ScopeTable.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
});
$("#spnrSave").hide();
$(document).on("click", ".btnAddEditScope", btnAddEditScope_click);
});

Asp.Net MVC jqgrid is not displaying my data

I am trying to fill a jqgrid. The grid is rendered but no data is displayed. I know my controller -- as called through a standard ajax function -- is working. It returns the data I'd expect.
How do I verify that jqgrid is returning the same data and what am I doing incorrectly that is not allowing the data to be dispayed?
jqgrid:
<script type="text/javascript">
jQuery(document).ready(function() {
$.ajaxSetup({ cache: false });
var rvtoken = $("input[name='__RequestVerificationToken']").val();
var ModuleId = #Dnn.ModuleContext.ModuleId;
var TabId = #Dnn.ModuleContext.TabId;
$('#grid').jqGrid({
url: '/DesktopModules/MVC/CW.GridTest/Item/getArtists2',
datatype: 'json',
mtype: 'POST',
contentType: 'application/json',
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader('ModuleId', ModuleId);
jqXHR.setRequestHeader( 'TabId', TabId);
jqXHR.setRequestHeader('RequestVerificationToken', rvtoken);
},
colNames: ['ArtistID', 'ArtistName', 'City'],
colModel: [
{ name: 'ArtistID', index: 'ArtistID', width: 80, align: 'left', editable: false },
{ name: 'Name', index: 'ArtistName', width: 120, align: 'left', editable: true },
{ name: 'Location', index: 'City',width: 60,align: 'left',editable: true}
],
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
loadOnce: true,
autoencode: true,
height: '100%',
rowNum: 10,
emptyrecords: 'No records',
sortname: 'ArtistID',
sortorder: 'desc',
viewrecords: true,
caption: 'Artists',
width: 300,
gridview: true,
jsonReader:
{
total: 'total',
page: 'page',
records: 'records',
root: 'rows',
repeatitems: false,
id: 'ArtistID'
}
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
Returned data from standard ajax:
{
"total":100,
"page":99,
"records":6,
"rows":"[
{\"ArtistID\":1,\"ArtistName\":\"Clayton Knight\",\"City\":\"Tigard\"},
{\"ArtistID\":2,\"ArtistName\":\"Corral Creek Bluegrass\",\"City\":\"Sherwood\"},
{\"ArtistID\":3,\"ArtistName\":\"Never Strangers Band\",\"City\":\"Portland\"},
{\"ArtistID\":5,\"ArtistName\":\"The Hillwilliams\",\"City\":\"Tigard\"},
{\"ArtistID\":7,\"ArtistName\":\"Bobo and the Bobbettes\",\"City\":\"Ellensburg\"},
{\"ArtistID\":27,\"ArtistName\":\"Bobo 5\",\"City\":\"Ellensburg\"}
]"
}
It was my controller. Not that it wasn't working but that it wasn't returning what I thought it should be. I was deserializing the data table for the "rows" element, and then deserializing the entire element again. So, the controller wasn't return a json string that jqgrid could actually work with.
It's all working now...
public String getArtists2()
{
using (var ac = new ArtistListingController())
{
ac.Gets();
ac.LoadDatatable();
DataView view = new DataView(ac.Datatable);
DataTable dt = view.ToTable(false, "ArtistID", "ArtistName", "City");
var jsonData = new
{
page=1,
total = 1, // (ac.RecordCount + rows - 1) / rows,
records = ac.RecordCount,
rows = dt //JsonConvert.SerializeObject(dt)
};
return JsonConvert.SerializeObject(jsonData);
}
}
Returning:
{
"page":1,
"total":1,
"records":6,
"rows":[
{
"ArtistID":1,
"ArtistName":"Clayton Knight",
"City":"Tigard"
},
{
"ArtistID":2,
"ArtistName":"Corral Creek Bluegrass",
"City":"Sherwood"
},
{
"ArtistID":3,
"ArtistName":"Never Strangers Band",
"City":"Portland"
},
{
"ArtistID":5,
"ArtistName":"The Hillwilliams",
"City":"Tigard"
},
{
"ArtistID":7,
"ArtistName":"Bobo and the Bobbettes",
"City":"Ellensburg"
},
{
"ArtistID":27,
"ArtistName":"Bobo 5",
"City":"Ellensburg"
}
]
}

jqgrid by using [WebMethod] inside aspx file

I'm using jqgrid for my project.
So far, jqgrid is ok while I'm using with ahsx file
But when I try to use [WebMethod] in aspx file, I get error 500.
Here is my jqgrid setting
$(document).ready(function () {
$("#JQGrid").jqGrid({
url: 'Testing.aspx/LoadMachineCapacity',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
datatype: "json",
postData: {},
height: 100,
autowidth: true,
loadtext: "Loading...",
colModel: [
{
name: 'MACHINEID',
index: 'MACHINEID',
label: 'Machine ID',
sortable: false,
editable: false
},
{
name: 'ISACTIVE',
index: 'ISACTIVE',
label: 'IS ACTIVE',
sortable: false,
editable: true
}],
loadonce: true,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
multiselect: false,
caption: 'Machines',
pager: '#JQGridPager',
pgbuttons: true, rowNum: 10, rowList: [10, 20, 30],
rownumbers: true,
viewrecords: true
, cellEdit: true
, afterEditCell: function (rowid, cellname, value, iRow, iCol) {
alert(value);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown + '\n' +
'errorDesc.: ' + jqXHR.responseText);
}
});
$("#JQGrid").navGrid('#JQGridPager',
{ view: false, edit: false, search: true, add: false, del: false, refresh: true }
);
});
and here is my server-side code
[WebMethod]
public static string LoadMachineCapacity(string pageIndex)
{
string Result = "";
try
{
string strOracleCnnString = ConfigurationManager.ConnectionStrings["PKERP"].ConnectionString;
OracleConnection oracleConn = new OracleConnection(strOracleCnnString);
string strSQL = " SELECT * " +
" FROM T_CT_MCCP " ;
OracleDataAdapter dataAdapter = new OracleDataAdapter(strSQL, oracleConn);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
Result = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
}
catch (Exception e)
{
Result = JsonConvert.SerializeObject(e.Message, Formatting.Indented);
}
return Result;
}
Thank in advance.
Thomas
There are a parameter at Webmethod.
However, your jqGrid setting not config at postData.
Change to postData: {pageIndex: "blabla"}.

Is there a way to disable cache on FullCalendar?

I'm using FullCalendar on asp.net application. I noticed that when FullCalendar receives data from SQL Server via Web-Method > JSON, it creates a cache file (EventList.json) inside browser history/temporary folder.
I have cache:false on every method but I don't know how to apply the same thing on events: calendar.asmx/EventList .
Please refer to my other post that shows how I receive my data via web-method.
So my questions are:
Is there a way to disable cache on events?
How can I use ajax like other methods to get data, because with this method I can disable cache
function runCalendar() {
var $modal = $('#event-modal');
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* Initialize the calendar */
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var form = '';
var today = new Date($.now());
var calendar = $('#calendar').fullCalendar({
slotDuration: '00:15:00',
/* If we want to split day time each 15minutes */
minTime: '08:00:00',
maxTime: '20:00:00',
timeFormat: 'HH(:mm)',
defaultView: 'agendaWeek',
events: "calendar.asmx/EventList",
lazyFetching: false,
allDaySlot: false,
firstDay: 1,
//weekends: false,
handleWindowResize: true,
//columnFormat:'ddd / DD',
selectHelper: true,
height: $(window).height() - 200,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
eventLimit: true, // allow "more" link when too many events
drop: function(date) {
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $categoryClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
if ($categoryClass) copiedEventObject['className'] = [$categoryClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
selectable: true,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form></form>");
form.append("<label>Change event name</label>");
form.append("<div class='input-group'><input class='form-control' type=text value='" + calEvent.title + "' /><span class='input-group-btn'><button type='submit' class='btn btn-success'><i class='fa fa-check'></i> Save</button></span></div>");
$modal.modal({
backdrop: 'static'
});
$modal.find('.delete-event').show().end().find('.save-event').hide().end().find('.modal-body').empty().prepend(form).end().find('.delete-event').unbind('click').click(function() {
calendar.fullCalendar('removeEvents', function(ev) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/DeleteCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "'}",
});
return (ev._id == calEvent._id);
});
$modal.modal('hide');
});
$modal.find('form').on('submit', function() {
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/UpdateCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "','title':'" + calEvent.title + "'}",
});
$modal.modal('hide');
return false;
});
},
eventDrop: function(event, ui, jsEvent) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/MoveEvents",
dataType: "json",
data: "{'id':'" + event._id + "','start':'" + moment(event.start).format("DD MMMM YYYY HH:mm:ss") + "','end':'" + moment(event.end).format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
eventResize: function(event, allDay) {
var allDay = !event.start.hasTime() && !event.end.hasTime();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/ResizeEvents",
dataType: "json",
data: "{'id':'" + event._id + "','end':'" + event.end.format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
select: function(start, end, allDay) {
$modal.modal({
backdrop: 'static'
});
form = $("<form></form>");
form.append("<div class='row'></div>");
form.find(".row")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Event Name</label><input class='form-control' placeholder='Insert Event Name' type='text' name='title'/></div></div>")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Category</label><select class='form-control' name='category'></select></div></div>")
.find("select[name='category']")
.append("<option value='busy'>Busy</option>")
.append("<option value='e1'>E1</option>")
.append("<option value='e2'>E2</option>")
.append("<option value='bg-blue'>Lunch</option>")
.append("<option value='bg-yellow'>Children</option></div></div>");
inputSelect();
$modal.find('.delete-event').hide().end().find('.save-event').show().end().find('.modal-body').empty().prepend(form).end().find('.save-event').unbind('click').click(function() {
form.submit();
});
$modal.find('form').on('submit', function() {
title = form.find("input[name='title']").val();
beginning = form.find("input[name='beginning']").val();
ending = form.find("input[name='ending']").val();
$categoryClass = form.find("select[name='category'] option:checked").val();
var allDay = !start.hasTime() && !end.hasTime();
if (title !== null && title.length != 0) {
//calendar.fullCalendar('renderEvent', {
// title: title,
// start:start,
// end: end,
// allDay: false,
// className: $categoryClass
//}, true);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/CreateCalendarEvent",
dataType: "json",
data: "{'title':'" + title + "','start':'" + start.format("DD MMMM YYYY HH:mm:ss") + "','end':'" + end.format("DD MMMM YYYY HH:mm:ss") + "','category':'" + $categoryClass + "','allDay':'" + allDay + "'}",
success: function(data) {
var obj = data.d;
if (obj == 'true') {
//$('#txtFirstName').val('');
//$('#txtLastName').val('');
//$('#txtCity').val('');
//$('#txtEmailID').val('');
//$('#lblmsg').html('Data Inserted Successfully');
}
},
error: function(result) {
alert(result);
}
});
calendar.fullCalendar('refetchEvents')
$modal.modal('hide');
} else {
alert('You have to give a title to your event');
}
return false;
});
calendar.fullCalendar('unselect');
}
});
/* Creation of new category */
$('.save-category').on('click', function() {
formCategory = $('#add-category form');
var categoryName = formCategory.find("input[name='category-name']").val();
var categoryColor = formCategory.find("select[name='category-color']").val();
if (categoryName !== null && categoryName.length != 0) {
$('#external-events').append('<div class="external-event bg-' + categoryColor + '" data-class="bg-' + categoryColor + '" style="position: relative;"><i class="fa fa-move"></i>' + categoryName + '</div>')
runCalendar();
}
});
}
$(function() {
runCalendar();
});
Instead of:
events: "calendar.asmx/EventList",
following method can disable the cache
eventSources: [{
url: 'calendar.asmx/EventList',
type: 'POST',
cache: false
}],
According to FullCalendar documentation your call already prevents the browser from caching, and the fact that FullCalendar is a jQuery plugin means that under the hood it probably uses jQuery's $.ajax() method to retrieve the data.
In my case I had to turn off both lazyFetching and events cache:
eventSources: [
{
url: ...,
cache: false,
}
],
lazyFetching: false

Resources