max limit of data fullcalendar can hold - c#

Is there a max amount of data that a bootstrap fullcalendar can hold. it seems to crash after 525 entries. It was working fine till it reached this limit.
It threw an error:
Error: {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
I am binding my data dynamically.
<script type="text/javascript">
$(document).ready(function () {
var events = [];
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Dashboard.aspx/GetEvents",
success: function (data) {
$.each(data.d, function (i, v) {
events.push({
title: v.Title,
start: moment(v.VCStartTime),
end: v.VCEndTime != null ? moment(v.VCEndTime) : null
});
})
GenerateCalendar(events);//binds data to calendar
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
//error: function (error) {
// alert('failed');
//}
})
Asp.net code for fetching data
[WebMethod]
public static List<events> GetEvents()
{
DataSet ds = new APIProcedure().ByProcedure("calendar_sp", new string[] { "key" },
new string[] { "getvalueForCalendar" }, "USPADDSETTING");
return ds.Tables[0].AsEnumerable().Select(datarow =>
new events()
{
Id = Convert.ToInt32(datarow["Id"]),
Title = Convert.ToString(datarow["Title"]),
Date = Convert.ToDateTime(datarow["Date"]),
StartTime = Convert.ToDateTime(datarow["StartTime"]),
EndTime = Convert.ToDateTime(datarow["EndTime"]),
}
).ToList();
}
public class events
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}

$(document).ready(function () {
$('#calendar').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
eventLimit: true,
eventColor: '#87c9f0',
events: function (start, end, timezone, callback) {//instead of getting all the data at once get data for visible part of calendar.
var Date1 = new Date(start);
let newdate = JSON.stringify(Date1);
newStartdate = newdate.slice(1, 11);
var Date2 = new Date(end);
let newdate2 = JSON.stringify(Date2);
newEnddate = newdate2.slice(1, 11);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'StartDate': '" + newStartdate + "', 'EndDate': '" + newEnddate + "' }",//send data to code behind and get data according to start and end date
url: "Dashboard.aspx/GetEvents",
success: function (data) {
var events = [];
$.each(data.d, function (i, v) {
events.push({
title: v.Title,
start: moment(v.VCStartTime),
end: v.VCEndTime != null ? moment(v.VCEndTime) : null
});
})
callback(events);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
})
}

Related

How can I call an ASP.Net string function with jQuery AJAX?

I have a string function ASP.Net Webform. I want to call this function using AJAX.
That function returns a string value from database with a month index
protected string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
var dataValue = { "month": 1 };
$.ajax({
type: "POST",
url: "Homepage.aspx/BringDatas",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
}
});
Give it a try:
Code Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
ajax call
$.ajax({
type: 'GET',
url: 'Homepage.aspx/BringDatas',
data: '{"month": 1}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (response) {
alert("Response: " + response.d);
},
error: function (response) {
}
});
This is javascript side
<script type="text/javascript">
$(document).ready(
function () {
$("#Gonder").click(
function () {
$.ajax
({
type: "POST",
url: "Homepage.aspx/OrnekPost",
data: "{'parametre':'1234'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (output) {
alert("Response: "+ output);
}, error: function () {
alert("hata var");
}
});
});
})
</script>
Codebehind.cs code
[ScriptMethod]
[WebMethod(EnableSession = true)]
public static string OrnekPost(string parametre)
{
return parametre + " değeriyle post işlemi gerçekleştirildi.";
}

Jquery UI Modal Dialog Not Working Properly

I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}

Loading events on start from database

I want to load all the events from the database in the calendar as the page loads but it's not working. Thedata is comming to the page from database but the object is not showing events.
My model is
public class Calendar
{
public int id { get; set; }
public string title { get; set; }
public DateTime starttime { get; set; }
public DateTime endtime { get; set; }
}
My controller methods are
[HttpPost]
public JsonResult dataReceiver(string title)
{
Calendar calendar = new Calendar();
calendar.title = title;
calendar.starttime = DateTime.UtcNow.ToLocalTime();
calendar.endtime = DateTime.UtcNow.ToLocalTime().AddDays(5);
db.Calendars.Add(calendar);
db.SaveChanges();
return Json(title, JsonRequestBehavior.AllowGet);
}
public ActionResult datasender()
{
var search = from m in db.Calendars select m;
//ViewBag.Message = search.ToList();
return Json(search.ToList(),JsonRequestBehavior.AllowGet);
}
and my view is
<html>
<head>
<title> Calendar</title>
<link href="~/Content/calendar/fullcalendar.css" rel="stylesheet" />
<link href="~/Content/calendar/fullcalendar.print.css" rel="stylesheet" media='print' />
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<style>
body {
margin: 40px 10px;
padding: 0;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
font-size: 14px;
}
#calendar {
max-width: 900px;
margin: 0 auto;
}
.fc-ltr {
background: #ddba8f;
}
.fc-toolbar {
background: #c64343;
}
</style>
</head>
<body>
<div id='calendar' style="height:90%; width:90%; color:black; border:1px solid blue; margin-top:5%; position:relative">
</div>
</body>
</html>
#section scripts
{
<script src="~/Scripts/calendar/moment.min.js"></script>
<script src="~/Scripts/calendar/jquery.min.js"></script>
<script src="~/Scripts/calendar/fullcalendar.js"></script>
<script src="~/Scripts/calendar/jquery-ui.custom.min.js"></script>
<script>
$(document).ready(function () {
calendarcreate();
var obj;
});
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
</script>
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
Just added following line in questions and calendar renders:
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});

How to fill a DropDown using Jquery Ajax Call?

I have a WebMethod which gets data that I want to fill DropDown with in a DataSet.
Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return ds.GetXml();
}
CLIENT SIDE(UPDATE 1):
<script type = "text/javascript">
function GetDropDownData() {
var myDropDownList = $('.myDropDownLisTId');
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(jQuery.parseJSON(data.d), function () {
myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
});
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
console.log(response.d);
alert(response.d);
}
</script>
function GetDropDownData() {
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data.d)
{
$.each(data.d, function (){
$(".myDropDownLisTId").append($("<option />").val(this.KeyName).text(this.ValueName));
});
},
failure: function () {
alert("Failed!");
}
});
}
var theDropDown = document.getElementById("myDropDownLisTId");
theDropDown.length = 0;
$.each(items, function (key, value) {
$("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));
here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.
From the WebMethod, don't send DataSet directly, send XML...
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
DataSet ds = new DataSet();
ds.Tables.Add("Table0");
ds.Tables[0].Columns.Add("OptionValue");
ds.Tables[0].Columns.Add("OptionText");
ds.Tables[0].Rows.Add("0", "test 0");
ds.Tables[0].Rows.Add("1", "test 1");
ds.Tables[0].Rows.Add("2", "test 2");
ds.Tables[0].Rows.Add("3", "test 3");
ds.Tables[0].Rows.Add("4", "test 4");
return ds.GetXml();
}
Before Ajax call...
var myDropDownList = $('.myDropDownLisTId');
Try like below...(inside Ajax call)
success: function (response) {
debugger;
$(response.d).find('Table0').each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
myDropDownList.append(option);
});
},
Note:
OptionValue and OptionText are the Columns of DataSet Table.
$(response.d).find('Table0').each(function (){}) - Here Table0
is the name of Table inside DataSet.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return DataSetToJSON(ds);
}
public static string DataSetToJSON(DataSet ds)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
return lstJson;
}
Ajax Call
function GetAssociation() {
var myDropDownList = $("#myDropDownLisTId");
var post_data = JSON.stringify({ "name": "xyz"});
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
json_data = JSON.parse(response.d);
myDropDownList.empty();
for(i=0; i<json_data.Table.length; i++)
{
myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
}
},
failure: function (response) {
alert(response.d);
}
});
}
// We can bind dropdown list using this Jquery function in JS script
function listDropdownBind() {
var requestId = 123;
$.ajax({
type: "POST",
url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
headers: { 'rId': requestId },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '';
var optionhtml1 = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$("#ddlName").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data.d[i].Value + '">' + data.d[i].Text + '</option>';
$("#ddlName").append(optionhtml);
});
}
});
};

jQuery autocomplete shows undefined values while WebService is returning correct data

$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D

Categories