ASP.NET Custom Validator + WebMethod + jQuery - c#

I'm trying to implement a .NET Custom Validator that uses $.ajax to query a WebMethod on the same page and return a boolean value to indicate whether the result is true or false.
The WebMethod I'm using is really simple
[WebMethod()]
public static bool IsPromoValid(string code)
{
string promoCode = "ABCDEFG";
bool result = code.ToLower() == promoCode.ToLower();
return result;
}
The CustomValidator looks like this
<asp:CustomValidator ID="cvPromoCode" Display="None" ControlToValidate="txtPromoCode" runat="server" ClientValidationFunction="validatePromo"
ErrorMessage="The promo code you entered is incorrect" OnServerValidate="ValidatePromoCode" />
And the simple $.ajax() ClientValidation function
function validatePromo(src, args) {
$.ajax({
type: "POST",
url: "Register.aspx/IsPromoValid",
data: "{'code': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
args.IsValid = msg.d;
}
});
}
The problem is that the page validates instantly and doesn't actually wait for the ajax call to finish. If there are any other errors on the page, it shows the Validation Summary with them, but never shows the error message from the Custom Validator.
I can see the AJAX call being made in Firebug, and it returs the right response (in this case true or false)

The easy way is by changing your validate to:
function validatePromo(src, args) {
var isValid;
$.ajax({
type: "POST",
url: "Register.aspx/IsPromoValid",
data: "{'code': '" + args + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
isValid = msg.d;
}
});
args.IsValid = isValid;
}
Take special note of the async:false. The reason your first try didn't work is that the ajax success callback was not getting called until after the validation scripts had already checked args.IsValid. With async:false, the $.ajax call won't complete until after the success callback is done.
The big issue with this is that it now "blocks" whatever js thread is running the validation. In the case of ASP.Net validators, I don't believe this is an issue but I would test it with a long-running call just to make sure you aren't screwing up your page for anyone on a slow connection.

Related

Apostrophe causes problems in AJAX method

I have a textbox (txtDescription) where the user can type a description when an event is canceled.
The problem is when the there is an apostrophe ' with in that textbox AJAX throws an error. Without the apostrophe it works and saves fine.
I have tried using JSON.stringify but this did not work.
This is my code:
$("#btnCancelEvent").click(function () {
var CencelDesc = $("#txtDescription").val();
var user = $("#lblFullName").html();
if (CencelDesc === "") {
alert("Please provide a reason why this schedule event is being canceled.");
return false;
} else {
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: "{'ScheduleID': '" + ScheduleID +
"','CentreID': '" + CentreID +
"','CencelDesc': '" + CencelDesc + //this is where the problem occurs
"','user': '" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
return false;
}
return false;
});
Please assist how I can fix this issue.
Two issues:
JSON uses double quotes, not single quotes.
Never buld JSON strings by hand. Instead, build an object and let JSON.stringify handle the escaping, etc., for you.
So:
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: JSON.stringify({ScheduleID: ScheduleID
,CentreID: CentreID
,CencelDesc: CencelDesc
,user: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
Side note: There's no need for dataType: "json" in that code. You're not doing anything with the response. In fact, in general, using dataType is an anti-pattern. Instead, ensure that the server sends back the correct Content-Type header.

.JQuery .ajax how do I call WCF method with return value?

I have been able to call WCF methods with .ajax. How do I call a method that returns a value? I need to call this method to see if data is ready and if not wait one second. The WCF method is:
[OperationContract]
[WebGet]
public bool IsDataReady(string requestGUID)
{
if (Global.publicDataDictionary.Keys.Contains(requestGUID))
return true;
else return false;
}
My JavaScript so far is:
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
}
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service never passes a requestGUID. Can't i use the same input variable?
var guid = "<%= this.guid%>";
// var input = '{"SbiId":"' + guid + '"}';
// var input = {requestGUID:"ca222cf7-be5e-431a-ab93-9a31e8ae2f4a"};
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service is never getting called:
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
else {
//Continue as data is ready
callUpdateGrid(input);
}
The return value will be contained in the data parameter passed to the success callback setup in your ajax call.
You will need to check the value here, then if false, setup a timeout, which on expiry will attempt the ajax call again.
It would be best IMO to wrap up the Ajax call inside a function, that you can call in a recursive fashion when the timeout has expired. e.g.
function CallIsDataReady(input){
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
if (!data){
setTimeout(function(){CallIsDataReady(input);}, 1000);
}
else{
//Continue as data is ready
}
}
});
}
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
CallIsDataReady(input);
});
When you view source on this page is:
var input = {requestGUID:"<%=guid %>"};
showing correctly in the javascript? If you put a breakpoint in your IsDataReady method, do you see if requestGUID has a value? Is your service on the same domain as the page calling it?
EDIT:
In your service change: [WebGet]
to:
[WebGet(
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
Read up on RESTful web services:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

jQuery ajax call doesn't seem to do anything at all

I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.

jquery postback using c# and asp.net returns null

I am attempting to use jquery to call a c# function when a button is clicked. What happens is the return variable (msg) is null.
The button code:
<button id="test1" runat="server">Get Text</button>
The JQuery code:
$(document).ready(function() {
$("#test1").click(function() {
$.ajax({
type: "POST",
url: "ServiceDirectoryAdd.aspx/GetCurrentDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
});
The C# function:
[WebMethod]
public static string GetCurrentDate()
{
return "foo";
}
As I said, the return variable, msg, returns null. Is there something I'm doing wrong?
EDIT: After placing a breakpoint in the C# function, it seems that the program is not entering the function.
Did you added script manager to page. If you not added it. Please add it and then script manager "EnablePageMethod" property to true.
Here is the link for that.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
try with indexing the msg
alert(msg[0]); or alert(msg.d);
Have you tried a GET?
$.get("ServiceDirectoryAdd.aspx/GetCurrentDate", function(data){
alert(data || data.d);
});
And edit the webmethod to accept get
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetCurrentDate()
{
return "foo";
}

Calling a c# methode from javascript/jquery and get the result

I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))

Categories