Reputation: 6868
I have two buttons, Front and Back, and one div :
<div id="data"></div>
Now when my page load I will display by default previous 24 hours data from a base date.
My Back and Front button:
<button type="button" id="btnForward" class="btn btn-default btn-xs">Forward</button>
<button type="button" id="btnBack" class="btn btn-default btn-xs">Forward</button>
when user clicks on back button then I would like to fetch previous 24 hours data and on click of forward button I would like to fetch forward 24 hours data.
I also want to prevent dates greater than the base date being returned.
This is my logic:
<script type="text/javascript">
var count = 0;
$(document).ready(function () {
MyFunction(Actions);
}
function MyFunction(Actions) {
// My ajax function call on Controller.
Parameters:Actions,count
}
$("#btnBack").click(function () {
Actions = "Back";
count++;
MyFunction(Actions);
});
$("#btnForward").click(function () {
Actions = "Forward";
// count--;
MyFunction(Actions);
// count++;
});
</script>
My controller:
public ActionResult Merge(string actionType=null,int count=0)
{
var date1 = new DateTime(2016, 2, 26,16,27,57);
DateTime Start= new DateTime();
if(!string.IsNullOrEmpty(actionType))
{
date1= date1.AddDays(-(count));
if (actionType == "Back")
Start = date1.AddDays(-1);
else
{
Start= date1.AddDays(1);
}
}
else
Start = date1.AddDays(-1);
var data = context.MyTable.Where(c => c.Date.Value > Start&& c.Date.Value <= date1);
}
In the above code I have successfully managed to get data correctly for back button but now struggling to get data when user clicks on forward button, and then I am not getting correct date.
Upvotes: 0
Views: 614
Reputation:
You controller method needs only one parameter, an int
to indicate the day(s) relative to your base date.
public ActionResult Merge(int days)
{
if (days > 0) // protect against malicious users
{
// return an error
}
var baseDate = new DateTime(2016, 2, 26,16,27,57);
DateTime EndDate = baseDate.AddDays(days);
DateTime StartDate = basedate.AddDays(days - 1)
var data = context.MyTable.Where(c => c.Date > StartDate && c.Date <= EndDate );
....
}
Then in the view, initialize a javascript variable for days
and increment/decrement based on which button is clicked
// initially disable the forward button
<button type="button" id="forward" class="btn btn-default btn-xs" disabled="disabled">Forward</button>
<button type="button" id="back" class="btn btn-default btn-xs">Back</button>
<script>
var days = 0;
var forward = $('#forward');
$('#forward').click(function() {
days++;
if (days == 0) {
forward.prop('disabled', true);
}
// call ajax function and pass value of `days` to the controller
});
$('#back').click(function() {
days--;
forward.prop('disabled', false);
// call ajax function and pass value of `days` to the controller
});
Upvotes: 1