How to load new data after click next or back Fullcalendar - c#

I am using Fullcalendar plugin which is integrated with my ASP.NET MVC project. My main task consists of creating a schedule of reservations. I have written the code which is responsible for displaying events("Buttons") for specific date, and it works fine!. Code below:
var calendar = $("#calendar").fullCalendar({
weekends: false
, lang: 'pl',
header: {
left:'',
center: 'title',
right: 'today prev,next'
}, height: 630, week: true, columnFormat: 'dd M/D', minTime: '8:00', maxTime: '20:00', selectable: true,
allDaySlot: false, eventColor: '#F6A828',
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
},
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
and method GetEvents in C#
public JsonResult GetEvents()
{
if (Session["DoctorID"] == null)
{
return Json(new { redirectUrl = Url.Action("Terminarz", "Recepcjonista"), isRedirect = true });
}
var listEvent = new List<CallendarEvent>();
List<CallendarEvent> list = TermRepository.GetAllEventsByDoctorId((int)Session["DoctorID"]);
int licznik = 1;
foreach (var item in list)
{
int count = Size(item.id, item.From, item.To);
for (int i = 0; i < count; i++)
{
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30)
});
licznik++;
}
}
var listEvent2 = from l in listEvent
select new
{
id = l.id,
//day = l.day,
//Title = l.Title,
start = l.From,
end = l.To,
color = "#88CD23"
};
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and now I would like to handle next and back buttons and change start date, end +7 day. I wrote something like this, but doesn't work
C#
public JsonResult GetEventsAdd(int move)
{
//all the same method as in GetEvents, but added days
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddDays(move),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30).AddDays(move)
});
licznik++;
}
}
//all the same method as in GetEvents
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and script was changed
events: function (start, end, timezone, callback) {
var data = { "move": 7 }
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
//data: JSON.stringify(calendar),
//datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
$(".fc-next-button").one("click", function () {
$.ajax({
url: '/Dentist/GetEventsAdd/',
type: 'POST',
data: JSON.stringify(data),
datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//$('#calendar').fullCalendar('refetchEvents');
}
});
});
how can I get such a solution?

The AJAX call that fullcalendar makes passes the start and end date range for the current view. It will then call that again, only if it doesn't have the date stored.
so in your /Dentist/GetEvents/
grab the "GET" variables: "START" and "END".
return the events that are in that range.
then simply use the native 'next', 'prev' buttons from fullcalendar and let it do its thing.

Related

Ajax call to controller is sending data, but i cannot use it if an if statement

Here is my controller. I am trying to pass the value through an if statement but it's not equalling (==) the string of "2019".
[HttpPost]
public ActionResult Extract(string[] response)
{
string statementQuery = "";
if (response!=null)
{
for (var i = 0; i < response.Length; i++)
{
if (response[i] == "2019")
{
statementQuery = "select statementPath from ClientStatements_Inventory where statementYear = '" + response[i] + "';";
}
}
}
Here is my ajax call. Is it something to do with the way it is sending to my controller? or my if statement?
$('#main-content-submit').click(function () {
var labelArray = [];
labelArray = $("input:checkbox:checked").map(function () {
return $(this).closest('label').text();
}).get();
console.log(labelArray);
event.preventDefault();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ response:labelArray }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert("Month and ear passed to controller");
},
error: function (err, result) {
alert("Error in Extract" + err.responseText);
},
});
return false;
});

How to send data object which contain upload files and string to controller using ajax?

I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}

Bings Maps - Read GeoJSON

I am working with the Bing Maps v8 API, trying to load my own GeoJSON onto a Bing Maps as in this example: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#geoJsonReadObject+JS
I am creating my JSON successfully (I have tested it using the Bing Maps Drag and Drop feature and all of my points show on the map. https://bingmapsv8samples.azurewebsites.net/#GeoJson%20Drag%20and%20Drop.
I am trying to get my GeoJSON to automatically load on a map, and I am receiving a JSON failure, and I am not sure why. (I am rather new to GeoJSON/JSON.)
Javascript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
var featureCollection = Microsoft.Maps.GeoJson.read(getGeoJson(), { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
function getGeoJson() {
$(function (callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
});
}
}
Controller:
[HttpPost]
public JsonResult PatGeoJSON(string parent)
{
JObject jsondata = JObject.FromObject(new
{
type = "FeatureCollection",
features = from p in pList
select new
{
type = "Feature",
geometry = new Geometry
{
type = "Point",
coordinates = new double?[] { p.GeoLocation.Longitude, p.GeoLocation.Latitude }
},
properties = new Properties
{
MemberName = p.MemberName,
/// etc...
}
}
});
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
My result is currently a "Failure" alert with the JSON string. Note: if I hardcode my GeoJSON as the result from the getGEOJSON function, all of my points show up on the map. Am I not reading the JsonResult correctly in my script?
Your getGeoJson function is asynchronous, so it doesn't return anything, this bing maps is receiving a null value to parse which it simply ignores and this no error. Specify a callback function when loading your geojson and when it responds, then read its value. Here is an updated version of your JavaScript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
getGeoJson(function(data){
var featureCollection = Microsoft.Maps.GeoJson.read(data, { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
});
function getGeoJson(callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
}
}

Auto-complete select multiple tags in asp.net

Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});

asp.net MVC pass server value to hidden field

From my OnePageCheckout.cshtml View i call ajax controller
#Html.Hidden("StepContent", (string)ViewBag.newAddress) #* never work *#
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: this.nextStep, // still stay in the same page
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
},
goto_section = "confirm_order"
});
}
How can I update the status of the hidden input with a value from the controller?
UPDATE 2:
var Billing = {
form: false,
saveUrl: false,
init: function (form, saveUrl) {
this.form = form;
this.saveUrl = saveUrl;
},
save: function () {
if (Checkout.loadWaiting != false) return;
Checkout.setLoadWaiting('billing');
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
this.nextStep; << nextStep won't be called !! but it works for success: this.nextStep
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
},
resetLoadWaiting: function () {
Checkout.setLoadWaiting(false);
},
nextStep: function (response) {
alert('aa');
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
$('#StepContent').val($("#billing-address-select").find('option:selected').text());
Checkout.setStepResponse(response);
}
};
Change status in JS after ajax call,
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
$("#StepContent").val(data.status);
this.nextStep;
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
and controller pass status in JSON
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel),
},
status = "abc",
goto_section = "confirm_order"
});
}

Categories

Resources