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

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 ;))

Related

ASP.NET + jQuery AJAX - getting 500 server error

I want to call an ASP.NET function from jQuery by AJAX with response.
I have file Controll.aspx where is included javascript code. Next I have /Services/ControllService.asmx, where is the function, which I want call from js.
js code:
$(document).ready(function () {
$('#btn_start').on('click', function () {
$.ajax({
type: "POST",
url: "Services/ControllService.asmx/Start",
data: {},
dataType: "json",
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (err) {
alert("Error:" + err.toString());
}
});
});
});
But I still getting the error 500.
POST http://localhost:56000/Services/ControllService.asmx/Start 500 (Internal Server Error)
k.cors.a.crossDomain.send
n.extend.ajax
Do you have any hints, what do I need to set e.g. in Web.config?
Many thanks.
SOLVED:
1 - I have defined Start function in ControllService.asmx.cs as static.
2 - I have badly configured data. It has to be named by the same way e.g. "sth".
In javascript it should be:
...
url: "Services/ControllService.asmx/Start",
data: JSON.stringify({ sth: "hahaha" }),
dataType: "json",
...
and in ControllService.asmx.cs -> method Start
public string Start(string sth){}
Many, many thanks for your hints.

Disable ASP:dropdownlist based on the selection of another ASP:Dropdownlist.value

I have two asp.net dropdownlists that I want to manipulate clientside with Javascript.
These two dropdowns are inside a modal open: function()
When dropdown1.value == "me"
I want dropdown2.value to be disabled
How can I accomplish this?
$(document).ready(function () {
if (document.getElementById('<%=dropdown1.ClientID%>').value == 'Me')
document.getElementById('<%=dropdown2.ClientID%>').disabled = true;
});
(optional) Part 2 I need to set an entity framework value to null after dropdown2 has been disabled how could I accomplish this without a postback?
Part 1:
$(document).ready(function ()
{
if($("#<%=dropdown1.ClientID%>").val() == "Me")
$("#<%=dropdown2.ClientID%>").prop("disabled",true);
});
Part 2 :
You would need to make an ajax call to a code behind or webservice to do that.
.ASPX
$.ajax({
type: "POST",
url: "PageName.aspx/CodeBehindMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (error) {
}
});
.ASPX.CS
[WebMethod]
public static void Test()
{
// Call EF code
}

.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.

ASP.NET Custom Validator + WebMethod + jQuery

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.

Categories