I have a problem with RadScheduler. I need to validate double clicked time slot for availability before insert form opens. I using advanced insert form. Unfortunately its no OnAppointmentInserting or like event like this. I found OnClientAppointmentInserting event, and i can use it for validation, but i can not continue to insert form if validation is correct. Following the code i use for client side validation, but its no way to show insert form after validation:
function beforeInserting(s, e) {
var url = '';
var requestUrl = window.location.href.toLowerCase();
if (requestUrl.indexOf('/views/') != -1)
url = requestUrl.substring(0, requestUrl.indexOf('/views/')) + '/jobservice.svc/IsTimeAvailable?userId=0';
e.set_cancel(true);
var app = e.get_targetSlot();
$.ajax({
url: url,
accepts: 'application/json, text/javascript, */*',
cache: false,
success: function (r) {
if (r != '') {
alert(r);
return;
}
else {
var scheduler = $find("<%= rdJobScheduler.ClientID %>");
var newApp = new Telerik.Web.UI.SchedulerAppointment();
newApp.set_start(app.get_startTime());
newApp.set_end(app.get_endTime());
// This is not working properly it just send OnInserted event to server
// scheduler.insertAppointment(newApp);
}
},
error: function (err, text, xhr) {
alert(text);
}
});
}
Please take a look at this Knowledge Base article of Telerik to see how to prevent inserting of appointment. In their case only if the subject of the appointment is empty - you cannot insert the appointment. You can use your own validation instead.
Related
When selecting an item from a bootstrap dropdown, I need to be updating a property on the page model to reflect the selection.
To achieve this, I'm doing an ajax post with jquery to the handler method:
function setStream(streamId, streamName) {
// If streamId is NaN or undefined, set to 0, assuming user is viewing all streams.
streamId = (streamId === NaN || streamId === undefined) ? 0 : streamId;
console.log(`setStream(${streamId}, ${streamName})`);
streamName = streamName === undefined ? "All streams" : streamName;
$("#Booking_Stream_Id").val(streamId);
$("#titleStream").html(`| ${streamName}`);
// Update the stream on the model.
const _streamId = parseInt(streamId);
$.ajax({
method: "GET",
url: "/Index?handler=Stream?newStreamId=" + _streamId,
headers: {
"RequestValidationToken": "#token"
},
error: function (data) {
console.log(data);
}
});
}
Dev tools shows the request succeeded:
Request URL: https://localhost:5001/Index?handler=Stream?newStreamId=0
Request Method: GET
Status Code: 200
But the breakpoint was never hit and the property never updated.
public async Task OnGetStream(int newStreamId)
{
logger.LogInformation("Current stream on booking is {stream}", this.Booking.Stream.Id);
var stream = await context.Streams.FindAsync(newStreamId);
if (stream is null)
{
// Assume user is attempting to view all streams.
this.Booking.Stream = new Stream { Id = 0, Name = "All streams" };
}
else
{
this.Booking.Stream = stream;
}
logger.LogInformation("NEW stream on booking is {stream}", this.Booking.Stream.Id);
}
Additionally my calls to the logger aren't being written to the console but that's more of a minor issue.
Given the above code, is there something I've done wrong here? I feel like this is dead simple stuff but for whatever reason I can't seem to get it working.
Any assistance will be appreciated.
url: "/Index?handler=Stream?newStreamId=" + _streamId,
You have a ? instead of & separating your query string values. Try this instead:
url: "/Index?handler=Stream&newStreamId=" + _streamId,
This is supposed to be easy, but I could not figure out how to do it. I have a textbox where a user will type a name to search for. Then, the user will have to provide some additional information such as selecting the state where the person live from a drop down. After the state is selected, I am doing an Ajax post to get a list of cities within that state. The issue is that as soon as the Cities are loaded, I lost the value that was typed in the textbox. How can I make this textbox persistent, so I don't loose the value?
function ValueSelected(state, city, zip) {
var SelectedState = state;
var SelectedCity= city;
var ZipCode= zip;
if (SelectedState.length > 0) {
// var url = '#Url.Action("SetState", "FindPerson")';
$.ajax({
url: '#Url.Action("SetState", "FindPerson")',
type: 'POST',
datatype: 'text',
data: { "SelectedState": SelectedState, "SelectedCity": SelectedCity, "ZipCode": ZipCode},
cache: false,
// contentType: 'application;text;charset=UTF-8',
success: function (e) {
window.location.href = window.location.href;
},
error: function (e) {
alert('error');
}
});
}
}
Update 08/07/2014 :
I write a function that will add the textbox value to a cookie when the user select something from the drop down. Then, I check the cookie to see if the cookie has something in it when the page is loaded. I set the cookie to expire after 30 minutes.
function setCookieInfo(name, value) {
if (name != null && name != "") {
setCookie(name, value, 24);
}
}
Since you are doing all of this client-side, I would not recommend doing window.location.href because that doesn't keep any of the client-side settings. Instead, you should handle everything on the client or setup a form in your view and call (note I'm using JQuery here) $("#form").submit() to post back the values. In that form you can have hidden fields to post back all the selected values, and reload them from the server.
Also, when you do an AJAX request, success returns anything, so your action can return:
return PartialView("XYZ");
And that HTML will be returned, which you can append to the UI. You can also return JSON, and build up the <select> item containing the cities.
It's not good to use window.location.href = ... because that makes constant get requests to the server, and you would have to pass the information in the querystring.
I am trying out the Kendo UI HTML Scheduler.
I was able to successfully read appointments from the database through my ASP.NET MVC appplication.
For Read : I am sending JsonResult from my ASP.NET controller.
For Update : The controller is getting a URL JSON encoded string which I deserialize and update the database and the return nothing to the caller.
When open an event to edit, make the changes and press "Save". The controller gets called and the record is updated but neither the pop-up window closes nor the scheduler gets updated.
The HTML Demo on Telerik website returns "callback()" on update and works fine but what am I missing on my code that would make the changes reflect.
**view**
<script>
$("#scheduler").kendoScheduler({
// configuration //
dataSource: {
batch: true,
transport: {
read: {
url : "http://localhost/Scheduler/Appointments",
dataType: "json"
},
update: {
Type:"POST",
url: "http://localhost/Scheduler/UpdateAppointment",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: JSON.stringify(options.models)};
}
}
},
schema: {
model: {
// my model
}
},
</script>
Controller
public JsonResult UpdateAppointment(String models)
{
if (models != null)
{
char[] charsToTrim = { '[', ']' };
string model_Trimmed = models.Trim(charsToTrim);
// Deserialize
Appointment SerializedAppointment = new JavaScriptSerializer().Deserialize<Appointment>(model_Trimmed);
Models.Entities.Appointment AppointmentToUpdate = db.Appointment.Where(x => x.TaskID == SerializedAppointment.TaskID).Single();
AppointmentToUpdate.Title = SerializedAppointment.Title;
AppointmentToUpdate.Start = SerializedAppointment.Start;
AppointmentToUpdate.End = SerializedAppointment.End;
db.SaveChanges();
}
return new JsonResult() {Data=null, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Kendo needs to return a valid JSON format in your paramater map, so you could try this:
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: JSON.stringify(options.models)};
}
return {};
}
Maybe this Link will also helps you...
(Copy just to prevent dead Links)
There is a breaking change with the new version of jQuery which affects the Kendo Q1 2013 version 2013.1.319
Since the empty result returned from the server in case everything is executed properly on the server side for the update and destroy requests, the error event of the dataSource is triggered because the empty result is not valid JSON.
The suggested resolutions when using the MVC Extensions are:
Use the Latest Internal Build version 2013.1.327
Change the response of the Update/Destroy actions from just serializing the ModelState to:
return Json(ModelState.IsValid ? new object(): ModelState.ToDataSourceResult());
I'm trying to make a booking system for Orchard by using the jQuery FullCalendar (Link to the jQuery FullCalendar).
I found this youtube tutorial on how to install FullCalendar as a Widget in Orchard and got it setup in 1.7.2 after a while.
Now I would like to be able to add and edit events from the site (currently it's setup so you have to add new events through the admin panel, same with editting).
I think the place where I have to start could be in this pastebin.
When I use the following code:
//dayClick: function(date, allDay, jsEvent, view) {
// if (allDay) {
// alert('Clicked on the entire day: ' + date);
// }else{
// alert('Clicked on the slot: ' + date);
// }
// alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
// alert('Current view: ' + view.name);
//},
And then click on a time on my calendar it tells me the date and so on (so the onclick event works), I'm just not sure how I should move on from that.
I would like to be able to just add an event from the calendar view atm. So far I have been able to add it, but not to save it to the database, I suppose it has something to do with:
var fullCalEvents = [];
var iterator = function (event) {
var newEvent;
newEvent = new Booking.Event(event.title, event.start, event.end, event.url, false);
fullCalEvents.push(newEvent);
};
But I'm not sure where to start.
The current select I have written is the one where I can add an event, but not save it in the database.
I can provide more information if need be!
I hope someone can enlighten me on how to do this.
Thank you
Casper
Lets give a try LeCattez,
I do not mess around with C# for a while, but you might know what i'm going to talk about.
In your handler class you will need to have something like this, this is from another question here in SO.
<%# WebHandler Language="C#" Class="MyHandler" %>
using System;
using System.Web;
public class MyHandler : IHttpHandler
{
public void ProcessRequest (HttpContext ctx)
{
var json = new JSONResonse()
{
Success = ctx.Request.QueryString["name"] != null,
Name = ctx.Request.QueryString["name"]
};
ctx.Response.ContentType = "application/json";
ctx.Response.Write(JsonConvert.SerialzeObject(json));
}
public bool IsReusable {
get { return false; }
}
}
In your handler you must fetch data sent from AJAX call. This is an example on how you can send data with Jquery.Ajax.
select: function(start, end, allDay, jsEvent, view){
$.ajax({
type: 'POST',
url: ajaxcallURL(_url,"2001"),
data: {"start":start,"end":end,"allDay":allDay }, //Here you can send data to server
beforeSend:function(){
//TODO do somethin before sendind data
},
complete:function(){
calendar.fullCalendar( 'refetchEvents' ); //This line will force hte calendar to re-get all eventSources
//wich means everytime you select a time period in calendar this will happen
},
success: function(data)
{
//TODO Do stuff with eventual data you need to send back to client
},
error: function(jqXHR, textStatus, errorThrown){
//Handle errors here
}
});
},//SELECT
Offcourse you can send to server an object, example an JSON object and fetch that object there like the example you see above.
No in the http Handler you will have to save to DB data.
Did you understood? Or you need further explanation? Let me know...
I have a handler StackOverFlow.cs like below:
public class StackOverFlow: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var nameValueCollection = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(encodedUrl));
//..
}
}
I get QueryString parameters with ParseQueryString.
How can I test it with jquery post? Is it possible?
For example below code use a URL which ends .ashx, is it possible to use with .cs?
How can I trigger my StackOverFlow class which inherits IHttpHandler with html POST?
<script type="text/javascript">
$(function () {
//we bind the submit click function
$("#btnSubmitJSON").click(function(){
var nameValue = $("#txtName").val();
var emailValue = $("#txtEmail").val();
var contactValue = $("#txtContactNo").val();
//we just use a quick check if the value are empty or not
if(nameValue != "" && emailValue != "" && contactValue != ""){
//we can hide the button just to make sure user does not click the button during the progress.
$("#btnSubmitJSON").show();
//we can output ajax icon loading so the user know it is in progress.
$("#output").html("<img src=\"/content/images/ajax-loader.gif\" /> Please wait, we are processing your request.");
//we build the json string
var jsonData = {
'Name': nameValue,
'Email': emailValue,
'Contact': contactValue
}
//note in order to proper pass a json string, you have to use function JSON.stringfy
jsonData = JSON.stringify(jsonData);
$.ajax({
url: "/ContactHandler.ashx", //make sure the path is correct
cache: false,
type: 'POST',
data: jsonData,
success: function (response) {
//output the response from server
$("#output").html(response);
//we clean up the data
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtContactNo").val("");
},
error: function (xhr, ajaxOptions, thrownError) {
$("#output").html(xhr.responseText);
$("#btnSubmitJSON").show();
}
})
}else{
$("#output").html("Please enter all fields.");
}
});
});
</script>
you need a collection of tests, an end to end test , an unit test for the javascript stubbed against a fake backend service and a unit test for the your handler, i can't give example but that is what is needed, there are lots of resources out there for unit testing C# code , javascript code and system end to end tests