I want to load an action result with javascript. I found some solution on stackoverflow, but they aint working.
I have this piece of code that when its friday it should load this view. It looks like this:
var from = jQuery('#orderForDate').datepicker().val().split("-");
var f = new Date(from[2], from[1] - 1, from[0]);
var n = f.getDay();
orderForDate = jQuery('#orderForDate').datepicker({ dateFormat: "dd-mm-yy" }).val();
if (n == 5) {
console.log('friday baby!');
var url = '#Html.Raw(Url.Action("Bestellen", "Cart", new { orderForDate=orderForDate}))';
window.location = url;
}
This is the controller is should load:
public ActionResult Bestellen(string orderForDate)
{
ViewBag.date = string.IsNullOrEmpty(orderForDate) ? DateTime.Now.Date : DateTime.ParseExact(orderForDate, "dd-MM-yyyy", CultureInfo.GetCultureInfo("nl-NL"));
User user = _db.Users.Find(_db.GetCurrentUserId());
var vm = new BestellenViewModel { ShowFavoritesAsDefault = user.ShowFavoritesAsDefault };
return PartialView(vm);
}
The problem is, when I click on a date that is friday in my datepicker, the browsers loads this url/page
http://localhost:54408/Cart/#Html.Raw(Url.Action(%22Bestellen%22,%20%22Cart%22,%20new%20%7B%20orderForDate=orderForDate%7D))
And I obviously don't get the desired page.
What am I missing here?
Read your url link. http://localhost:54408/Cart/#Html.Raw(Url.Action(%22Bestellen%22,%20%22Cart%22,%20new%20%7B%20orderForDate=orderForDate%7D)). It is not what you want. Try: window.location = '/Cart/Bestellen?orderForDate=' + orderForDate
Related
Good day. I have read and done almost all of the solution in the questions but cant seem to solve my problem. As written in my question, in mvc, i am passing a value from controller to view a string and then get by javascript to run a modal if ever a certain condition is met. please help. thanks.
here is the code in my controller:
public ActionResult Series()
{
List<sample> series = db.samples.Where(x => x.status == "False").ToList();
if ( series.Count == 0)
{
ViewBag.Info = "None";
}
else {
ViewBag.Series = series;
ViewBag.Info = "Have";
}
return View();
}
My View:
<input type="text" value="#ViewBag.Info" id="info" name="info" />
My Javascript:
#section Scripts{
<script>
$(window).on('load', function () {
var modelll = document.getElementById("#(ViewBag.Info)").value;
var s_end = document.getElementById("myNumber2").value;
var s_current = document.getElementById("myNumber3").value;
var s_status1 = document.getElementById("status").value;
var s_id1 = parseInt(document.getElementById("myNumber").value);
var s_end2 = parseInt(s_end, 10);
var s_current2 = parseInt(s_current, 10);
var x = parseInt(s_current, 10) + 1;
document.getElementById("item1").value = s_id1;
document.getElementById("item2").value = s_end;
document.getElementById("item3").value = x;
document.getElementById("status2").value = s_status1;
if (modelll === 'Have')
{
if ((s_current2 > s_end2) && (s_current2 != s_end2)) {
$('#myModal').modal({ backdrop: 'static', keyboard: false });
$('#myModal').modal('show');
}
}
else
{
$('#myModal').modal({ backdrop: 'static', keyboard:false });
$('#myModal').modal('show');
}
});
</script>
}
getElementById need an ID but you are passing #ViewBag.Info. change it to :
var modelll = document.getElementById("info").value;
also you are making many extra variables which are not really needed. for example to get what you have in s_current2, you can use
var s_current = parseInt(document.getElementById("myNumber3").value, 10);
no need to create another variable to convert it to integer.
To get the value from textbox
var modelll = document.getElementById("info");
To set the value to textbox
document.getElementById("info").value = var modelll;
you are using #ViewBag.Info instead of element id.
Following line is causing the problem in your code :
var modelll = document.getElementById("#(ViewBag.Info)").value;
// document.getElementById needs Id but you are passing #(ViewBag.Info) which is wrong
var modelll = document.getElementById("info").value; //info id of your textbox
// now check
if (modelll === 'Have')
{ }
else
{ }
I want to get a range of items between dates from two JQuery calendars and then update the view when I press a submit button so that I only see the items between the selected dates. I'm not sure I'm going about things the best way.
My plan was to:
Get the user to select the dates in the calendars.
Use Javascript to return the dates as variables.
Send the variables to a controller which would then return a new view.
My code is below and my question is really in two parts.
Is there a better way to do this?
If this is ok, how can I get the javascript variables into the ActionLink to pass back to the controller?
Thanks in advance!
Controller:
// GET: Home
public ActionResult IndexDateRange(string sortOrder, DateTime startDateFromJS, DateTime endDateFromJS)
{
var sortedByDates = from pay in db.DailyPayments
select pay;
sortedByDates = sortedByDates.OrderByDescending(pay => pay.Date);
var first = sortedByDates.Select(pay => pay.Date).First();
var lastDate = sortedByDates.Select(pay => pay.Date).Last();
if (startDateFromJS > first.Date || (endDateFromJS < lastDate))
{
var dateRange = sortedByDates.Where(pay => pay.Date >= startDateFromJS && pay.Date <= endDateFromJS);
return View(dateRange.ToList());
}
return View(sortedByDates.ToList());
}
Javascript in the Index:
#Html.ActionLink("Get Dates", "IndexDateRange", routeValues: new { startDateFromJS = startDate, endDateFromJS = endDate })
<script>
$(function () {
var startDate = getStartDate();
var endDate = getEndDate();
function getStartDate() {
$('#startDate').datepicker();
$('#calendarSubmitButton').click(function () {
//var startDate = $('#startDate').datepicker('getDate');
var startDate = $('#startDate').datepicker('getDate');
console.log(startDate);
return startDate;
})
};
function getEndDate() {
$('#endDate').datepicker();
$('#calendarSubmitButton').click(function () {
var endDate = $('#endDate').datepicker('getDate');
console.log(endDate);
return endDate;
})
};
Temporary Test JS to try and wire up the href. When I click on it, it just adds the pound symbol to the home/index Url and in the browser developer tools it says illegal character.
Get Dates
<script type="text/javascript">
$('#calendarSubmitButton').click(function() {
var tempStartDate = #DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");
var tempEndDate = #DateTime.Now.ToString("yyyyMMdd");
location.href='#Url.Action("IndexDateRange")+'?startDateFromJS='+$('tempStartDate')+'&endDateFromJS='+$('tempEndDate')';
});
</script>
Screen Grab:
Screenshot of the setup
Try this
Get Dates
<script type="text/javascript">
$('#calendarSubmitButton').click(function() {
var tempStartDate = '#DateTime.Now.AddMonths(-1).ToString("yyyyMMdd")';
var tempEndDate = '#DateTime.Now.ToString("yyyyMMdd")';
location.href='#Url.Action("IndexDateRange")?startDateFromJS='+tempStartDate +'&endDateFromJS='+tempEndDate;
});
</script>
Thanks to the help of #StephenMuecke and #Tanmay, I was finally able to get this to work. I'm posting the functioning code here.
Controller
// GET: Home
public ActionResult Index(string sortOrder, string startDate, string endDateFromJS)
{
var sortedByDates = from pay in db.DailyPayments
select pay;
sortedByDates = sortedByDates.OrderByDescending(pay => pay.Date);
if (startDate != null && endDateFromJS != null)
{
DateTime convertedStartDateFromJS = DateTime.ParseExact(startDate, "yyyyMMdd", new CultureInfo("en-US"));
DateTime convertedEndDateFromJS = DateTime.ParseExact(endDateFromJS, "yyyyMMdd", new CultureInfo("en-US"));
var dateRange = sortedByDates.Where(pay => pay.Date >= convertedStartDateFromJS && pay.Date <= convertedEndDateFromJS);
return View(dateRange.ToList());
}
return View(sortedByDates.ToList());
}
Javascript and HTML in the index.cshtml
<div class="form-group">
#Html.Label("Total payment:", new { id = "totalTextbox" }) <br />
#Html.TextBox("Total", Math.Floor(totalPayment) + " yen" , new { #class = "alert alert-danger", #readonly = "readonly" })
</div>
<div class="form-group">
#Html.Label("Starting Date:")
#Html.TextBox("Starting Date:", "", new { #class = "date-picker", id = "startDate" })
#Html.Label("Ending Date:")
#Html.TextBox("Ending Date:", "", new { #class = "date-picker", id = "endDate" })
#*<input type="submit" href="#" id="calendarSubmitButton" class="btn btn-primary" />*#
Get Dates
<script type="text/javascript">
$(document).ready(function () {
$('#calendarSubmitButton').click(function () {
//TODO: Figure this out.
var tempStartDate = $("#startDate").val($.datepicker.formatDate('yymmdd', new Date($('#startDate').datepicker('getDate'))));
var tempEndDate = $("#endDate").val($.datepicker.formatDate('yymmdd', new Date($('#startDate').datepicker('getDate'))));
location.href = '#Url.Action("Index")?startDate=' + tempStartDate.val() + '&endDateFromJS=' + tempEndDate.val();
})
});
</script>
</div>
I am trying to fetch events from my LocalDB server and have them display on my calendar, but they aren't appearing.
I am using the following method to fetch the events.
public JsonResult GetEvents(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = from e in db.Events
select new
{
ID = e.ID,
Title = e.Title,
StartDate = e.StartDate.ToString("s"),
EndDate = e.EndDate.ToString("s"),
EventType = e.EventType,
Hours = e.Hours,
AllDay = true
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
My calendar is rendered as follows:
#Styles.Render("~/Content/fullcalendar")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/fullcalendar")
<br />
<div id="calendar"></div>
<br />
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: 'title',
center: '',
right: 'prev,next today' },
defaultView: 'month',
weekends: false,
editable: false,
events: "/Home/GetEvents/" });
});
</script>
Any help is greatly appreciated.
EDIT:
This is in my web console:
no element found abort:1:1
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. browserLink:37:40278
no element found send:1:1
no element found send:1:1
no element found send:1:1
no element found
GET http://localhost:54802/Home/GetEvents/ [HTTP/1.1 500 Internal Server Error 10ms]
Your response is not conform to fullCalendar expected output. If you see the doc, you understand that each events needs to have at least these parameters:
title
start
In your case the code should be like this:
public JsonResult GetEvents(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = from e in db.Events
select new
{
id = e.ID,
title = e.Title,
start = e.StartDate.ToString("s"),
end = e.EndDate.ToString("s"),
eventType = e.EventType,
hours = e.Hours,
allDay = true
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
The first problem is, as I think, the name of variables for each event. This not match what fullCalendar is expecting.
With this new one GetEvents method fullCalendar should understand and print your output.
#Html.ActionLink("Search", "GetDateWiseGuestReport", "Reports", new { StartDate = "sss",EndDate="eee" }, new { #id = "btnDateWiseGuestSearch", #class = "btn btn-red" })
$("#btnDateWiseGuestSearch").bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = this.href.replace("sss", StartDate);
this.href = this.href.replace("eee", EndDate);
});
Okay i am using above code to change the Action-link URL at run time.Everything is running smoothly. but i have a strange issue i.e. when i click the button 1st time its gets the values from text boxes and change accordingly, but when i press button again its doesn't get new values from text boxes rather its somehow using OLD VALUES that i inputted 1st time!
Because after the firs click you are replacing the sss and eee from the href so there after is no sss or eee in the href. So nothing is replaced after the first click
So a possible solution is to store the original href value somewhere else then use that for replacing the content. In the below solution the data api is used to store the original value
var $btn = $("#btnDateWiseGuestSearch");
$btn.data('href', $btn.attr('href'))
$btn.bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
var href = $(this).data('href');
this.href = href.replace("sss", StartDate).replace("eee", EndDate);
});
Basically in your jQuery code you are create a new link by replacing sss and eee however once you have replaced them that is it, you won't find them again
this.href = this.href.replace("sss", StartDate); // sss no longer exists after this
this.href = this.href.replace("eee", EndDate); // sss no longer exists after this
What you will need to do is store the original href value before you modify it and then reference that when you want to update the link
$("#btnDateWiseGuestSearch").bind('click', function () {
var $this = $(this);
var originalhref = $this.data("href");
if(!originalhref){
this.data("href", this.href);
}
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = originalhref.replace("sss", StartDate).replace("eee", EndDate);
});
I would like to make redirect when a date is changed and transmit selected date parameter (via window.location.href). I'm using Bootstrap Date Paginator, which contains Bootstrap datepicker, but I don't know how to change these lines of code to work properly:
this.$calendar
.datepicker({
options...
})
.datepicker('update', this.options.selectedDate.toDate())
.on('changeDate', $.proxy(this._calendarSelect, this));
I know I would use changeDate event but there aren't any examples of using this event. Can you help me, please?
Would this do?
You can use .on('change', ..) like this,
this.$calendar
.datepicker({
options...
}).on('change', function() {
var changedDate = this.$calendar.val();
//alert("value of date is "+ x);
var theUrl = 'your URL';
window.location.href = theUrl+"date="changedDate
});
Else use, on('change.dp', ..) event like this,
this.$calendar
.datepicker({
options...
}).on('change.dp', function() {
var changedDate = this.$calendar.val();
//alert("value of date is "+ x);
var theUrl = 'your URL';
window.location.href = theUrl+"date="changedDate
});
Alternatively have a look at this too.
May be it's too late, but I have same problem and come up with this solution,
while setting options for Bootstrap Date Paginator keep track of onSelectedDateChanged function and assign the date value to a variable and send that variable to location.href.
<script>
var currDate = new Date();
var options = {
selectedDateFormat: 'DD/MM/YYYY',
selectedDate: moment(currDate).format('DD/MM/YYYY'),
onSelectedDateChanged: function (event, date) {
var dateSelected = moment(date).format('DD/MM/YYYY');
location.href = '/ServletName?timestamp='+currDate .getTime() + "&date=" + dateSelected ;
},
};
$('#paginator').datepaginator(options);
</script>
<body>
<div id="paginator"></div>
</body>