Run a method in controller according to datepicker value - javascript

I want run the method Index in the Home Controller according to the date selected in datepicker,
Here is my View code:
<input type="text" name="date" class="datepicker" id="calendar" />
$("#calendar").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (date, instance) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home")/' + date,
success: function (data) {
if (data.success) {
alert(date)
}
}
})
}
}).datepicker("setDate", new Date());
I want when I choose a date in my datepicker run this Method:
[Route("Home/{date?}")]
public ActionResult Index( DateTime? date = null)
the problem is the Ajax call this URL: Home\12-04-2018when I choose the 12-04-2018 instead of /Home/Index/12-04-2018 is my code wrong or am I missing something? thanks for help.

Update your code as below, this should work for you. Date has been passed as query string
Script
$("#calendar").datepicker('setDate', 'today');
$("#calendar")
.datepicker({ dateFormat: 'dd/mm/yy' })
.on("changeDate", function (e) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home") + '?date='+ e.date,
success: function (data) {
if (data.success) {
alert(e.date)
}
}
});
});
And action method:
[HttpGet]
public ActionResult Index( DateTime? date = null)
Update:
To change the date format in view, build new date string from date object that C# can parse
var newDate = e.date.getUTCMonth() + 1 + '/' + e.date.getUTCDate() + '/' + e.date.getUTCFullYear() + ' 00:00:00';
and pass it as parameter to controller.

Related

Large amount of events loaded on the angularjs-bootstrap-calendar

I'm pulling in ALL my event data from my server and since I have a lot of events to pull, the angular-bootstrap-calendar takes a lot of time to load.
I was wondering if its possible to pull only a month's worth of data for the current view I'm in (month, week, day..I would hide the year view). As I change the view to the next month, I'd pull the data for that month only.
Right now, I pull ALL the data only once, when the calendar loads, but not sure how to pull the data when the view changes.
var urlapievents = $location.protocol() + "://" + $location.host() + "/api/events/" ;
$http.get(urlapievents).success(function(events) {
Good solution for me
Get year and month of view, send it to API, and only retrieve events for that year-month:
js
vm.viewChangeClicked = function() {
var viewDateYearMonth = moment(vm.viewDate).format('YYYY-MM');
var urlapieventsall = $location.protocol() + "://" + $location.host() + "/api/events/" + viewDateYearMonth ;
$http.get(urlapieventsall).success(function(events) {
vm.events = events.events;
});
};
html
<div class="col-md-6 text-center">
<div class="btn-group">
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'month'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Month</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'week'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Week</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'day'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Day</label>
</div>
</div>
I've also added logic to check if previous yyyy-mm is equal to current yyyy-mm to save some unnecessary calls to the API.
If you grab your events as a json feed, you can use additional options - startParam and endParam. They can be used like this:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
if (request) {
request.abort();
};
$.mobile.loading('show');
request = $.ajax({
type: "POST",
url: "../Services/Calendar/CalendarService.asmx/GetEvents",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ dtStart: " + JSON.stringify(start) + ", dtEnd: " + JSON.stringify(end) + "}",
success: function(data) {
var events1 = [];
$(data.d).each(function() {
events1.push({
title: this.Title,
start: this.Start,
end: this.End,
id: this.Id
});
});
callback(events1);
$.mobile.loading('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText == 'abort') {
$.mobile.loading('hide');
return;
} else {
alert('There was an error');
$.mobile.loading('hide');
}
}
});
}
});
You can read more about those parameters here: https://fullcalendar.io/docs/event_data/events_json_feed/
The functionality you describe is a sort of date pagination, although this functionality isn't built in (shame, because it sounds really useful), you can implement your own with some small amount of work
First, the datepicker stores a JS Date object inside the ng-model, you can $watch it and get the current year/month/day out of it
$scope.modelDate = new Date()
...
$scope.$watch('modelDate', function(newDate, oldDate) {
newDate.getDay(); // 5
newDate.getMonth(); // 11
newDate.getYear(); // 116
})
Now you can query your database to get all the event for your selected month
Also, you can utilize the datepicker's mode (showing wether you are viewing the datepicker in the day/month/year mode, you set it up inside the options object).
datepickerMode C (Default: day) - Current mode of the datepicker (day|month|year). Can be used to initialize the datepicker in a specific mode.
Using this property you can query a month, year or years of events.

Bootstrap datepicker beforeShowday works only on first change

I'm trying to disable booked dates on datepicker. My code simply posts an ID to ajax.php file and i run a mysql query based on that id and get start and end dates. then i make an array that contains these dates and the ones in between. Finally I get this json_encoded array and it basically defines dates to be disabled on my bootstrap datepicker. I have recently found out that nothing is wrong with $.post method and changed the title. The problem was beforeShowday, it doesn't rerun after changes. Here is the jQuery code:
$.ajaxSetup({ cache: false });
var date = new Date();
date.setDate(date.getDate());
function getJsonRes(urlid){
var tarihler = [];
var url="ajax.php";
$.post( url, {"id":urlid}, function(data) { //this is the post request
$.each( data, function(key, val) { //to retrieve json encoded data
var tarih=val;
tarihler.push(tarih);
});
var disabledDays = tarihler;
function daysDisabled(date) {
for (var i = 0; i < disabledDays.length; i++) {
if (new Date(disabledDays[i]).toString() == date.toString()) {
return false;
}
}
return true;
}
$('#grs').datepicker({ //this is start date
language:'tr',
todayHighlight:true,
weekStart: 1,
startDate:date,
autoclose: true,
format: 'dd-mm-yyyy',
beforeShowDay: daysDisabled
})
.on('changeDate', function (selected) {
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf()))+1);
$('#cks').datepicker('setStartDate', startDate);
});
$('#cks').datepicker({ //this is end date
todayHighlight:true,
weekStart: 1,
language:'tr',
autoclose: true,
format: 'dd-mm-yyyy',
beforeShowDay: daysDisabled
})
.on('changeDate', function (selected) {
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('#grs').datepicker('setEndDate', FromEndDate);
});
}, "json");
}
$('#choice').change(function(){
var idvalue=$(this).val();
getJsonRes(idvalue);
});

send jquery var to php in my code

.js code is loaded on index.php load. I want to send [date var] to php
$(function() {
$('#datepicker').datepicker( {
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
showButtonPanel: true,
numberOfWeek: 0,
dateFormat: 'yy-mm',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
var date = year +'-'+month;
var newDate = new Date(year, month, 1)
$(this).datepicker('setDate',newDate);
}
});
});
You can place whatever you want to send in reqObject. You can access this object in you php code as the requestBody.
Call back is the function you want to execute after you get response from the server.
url is noting but the url to which you are posting your data
var reqObject = {"newDate":newDate}
var type = 'POST'
var url = "your post url"
var callback = function(data){
console.log(data)
//Your code goes here
}
sendData(type,reqObject,url,callBack);
sendData: function(type,reqObject,url,callBack) {
$.ajax({
type: type,
data: reqObject ,
dataType: "json",
url: url ,
success: function(response){
callBack(response);
}
});
}

Calling Controller's method from Javascript in View

I am trying to access a method in the controller by Javascript from View
<div id="Historicaldata">
From Date <input type="date" id="fromDate" /> To Date <input type="date" id="toDate" />
Export to Excel
</div>
<script>
function GetFromDate() {
var dt1 = document.getElementById('fromDate').value;
var dt2 = document.getElementById('toDate').value;
var url = "~/GeneralStatics/Excel/" + "startdate=" + dt1 + "/endDate=" + dt2;
alert(url);
window.location.href = this.href + "startDate=" + document.getElementById('fromDate').value + "&endDate=" + document.getElementById('toDate').value;
return false;
};
</script>
In my controller there is avoid method like this:
public void Excel(DateTime startDate, DateTime endDate)
by which an Excel file will be downloaded.
what is the best way to do this?
and is it possible doing it without redirection?
You don't need javascript, you could put the input fields inside an HTML form instead:
#using (Html.BeginForm("Excel", "SomeControllerName", FormMethod.Post))
{
<div id="Historicaldata">
From Date <input type="date" name="startDate" />
To Date <input type="date" name="endDate" />
<button type="submit">Export to Excel</button>
</div>
}
Also make sure that your action arguments are matching the names of the input fields and don't forget that in ASP.NET MVC, contorller actions must return ActionResults, not void:
public ActionResult Excel(DateTime startDate, DateTime endDate)
{
...
}
Use AJAX to download the file:
$.ajax({
url: '#Url.Action("Excel", "GeneralStatics")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
type: "GET",
success: function () {
window.location = '#Url.Action("Excel", "GeneralStatics", new { #startDate= dt1 , #endDate = dt2 })';
}
});

Using Jquery inside of Razor

I'm trying to pass a string from javascript to a razor ActionLink
string filtering =$("#Hello").val();
#Html.ActionLink(Name, ControllerName, new { sort = columm, order = orderby, filters = filtering })
but I'm not able to access to this variable, I already try #:filtering or "#filtering" but doesn't work anyway,
How can I pass the variable to the controller?
If you want to send or post the data to Controller's Action then you may try this...
<input type="submit" id="btnFilter" value="Filter" name="btnFilter" />
$('#btnFilter').click(function () {
var sort = sortValue;
var order = orderValue;
var filter= filterValue;
$.ajax({
type: 'POST',
url: '#Url.Action(ActionName, ControllerName)',
data:'{"sort":"' + sort+ '","order":"' + order+ '","filter":"' + filter+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function () {
}
});
});
then.... in controller action
public ActionResult ActionName(string sort ,string order , string filter)
{
// do Something here....
}
You'd have to add the parameter to the URL yourself manually using jQuery to assign the href attribute of the anchor tag.
First, let's take off the filter parameter off your ActionLink and give it an ID (so we can reference it in jQUery):
#Html.ActionLink(Name, Controller, new { sort = columm, order = orderby }, new { id = "myLink" })
Then do the following jQuery:
$(function () {
var newLink = $("#myLink").attr("href") + "?filter= " + $("#Hello").val();
$("#myLink").attr("href", newLink);
});
the way that I could do it was passing the Url to the controller
window.location = window.location.protocol + "//" + location.host + "/Name/Controller/" + "?sort=sort" + "&order=order" + "&page=page" + "&filters=" + filter;

Categories

Resources