How to consume the return value of a webservice in jquery ajax call? - asp.net

I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
return input.IsNationalCode();
}
I call it from an aspx page by jquery ajax function :
$('#txtNationalCode').focusout(function () {
var webMethod = "../PMWebService.asmx/IsValidNationalCode";
var param = $('#txtNationalCode').val();
var parameters = "{input:" + param + "}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.responseText == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
},
error: function () {
$('#status').html("error occured");
}
});
});
But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work

Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
if (msg.d == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
}
For "d" explanation follow this link: Never worry about ASP.NET AJAX’s .d again

Related

WebMethod access page control and set value

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?
WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});
You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.
You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

Unknown web method in asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}
You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});
Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

Using Ajax in a .net project to call a .aspx.cs function NOT WORKING

Im using Ajax in a .net project (isn't MVC.net). I want to call a function of my .aspx.cs from a JScript Function.
This is my JScript code:
$("a#showQuickSearch").click(function () {
if ($("#quick_search_controls").is(":hidden")) {
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{showQuickSearch}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
}
});
$("#quick_search_controls").slideDown("slow");
$("#search_controls").hide();
$("#search").hide();
} else {
$("#quick_search_controls").hide();
}
});
And this is my .aspx.cs Function:
[WebMethod]
public string SetInfo(string strChangeSession)
{
Label1.Text = strChangeSession;
return "This is a test";
}
The problem is that my .aspx.cs function is not being called and isn't updating the label.text.
Try making your function static.
[WebMethod]
public static string SetInfo(string strChangeSession)
{
//Label1.Text = strChangeSession; this wont work
return "This is a test";
}
data: "{showQuickSearch}" is not valid JSON.
Here's how a valid JSON would look like:
data: JSON.stringify({ strChangeSession: 'showQuickSearch' })
Also your PageMethod needs to be static:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "This is a test";
}
which obviously means that you cannot access any page elements such as labels and stuff. It is inside your success callback that you could now use the result of the PageMethod to update some label or whatever.
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{'strChangeSession':'showQuickSearch'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
});
And your backend code:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "Response ";
}

pass an array in jquery via ajax to a c# webmethod

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
$(".jobRole").each(function (index) {
var jobRoleIndex = index;
var jobRoleID = $(this).attr('id');
var jobRoleName = $(this).text();
var roleInfo = {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
};
queryStr = { "roleInfo": roleInfo };
jobRoleArray.push(queryStr);
});
My ajax code
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: jobRoleArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
Not sure on the webmethod but here is what I'm thinking:
[WebMethod]
public static bool save_Role(String jobRoleArray[])
You will be passing an array of:
[
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
},
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
}, ...
]
And in my opinion, it would be easier if you have a class that matches that structure, like this:
public class roleInfo
{
public int roleIndex{get;set;}
public int roleID{get;set;}
public string roleName{get;set;}
}
So that when you call your web method from jQuery, you can do it like this:
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
And in your web method, you can receive List<roleInfo> in this way:
[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{
}
If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.
I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-
function PostAccountLists() {
var accountLists = new Array();
$("#participantLists input[id*='chkPresents']:checked").each(function () {
accountLists.push($(this).val());
});
var instanceId = $('#<%= hfInstanceId.ClientID %>').val();
$.ajax({
type: "POST",
url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
In the code behind page (the web method)
[WebMethod]
public static void SignOff(object participantLists, string insId)
{
//subscription row id's
string[] a = participantLists.ToString().Split(',');
List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();
int instanceId = Convert.ToInt32(insId);
The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.
Hope this helps.
EDIT:-
according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success
function AjaxSucceeded(result) {
var res = result.d;
if (res != null && res === true) {
alert("succesfully posted data");
}
}
Hope this helps
Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:
JSON.stringify(<your array cames here>)
for example, if you would like to call a web page with array as parameter you can use the following approach:
"<URL>?<Parameter name>=" + JSON.stringify(<your array>)

spring.net + nhibernate + jquery ajax call to webmethod at codebehind

I am trying to make a jquery ajax call to a static method on the codebehind file. The problem is that ArtistManager injected by Spring is not static and I cannot use it in the static webmethod. I am looking for any ideas on how to implement this
ArtistList.aspx
$(document).ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "ArtistList.aspx/GetArtists",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
alert("Success: " + msg.d);
},
error: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("Error: " + msg.d);
}
});
});
});
ArtistList.aspx.cs
private IArtistManager artistManager;
public IArtistManager ArtistManager
{
set { this.artistManager = value; }
get { return artistManager; }
}
protected long rowCount = 0;
.
.
.
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
//return ArtistManager.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Assuming a single context, in which an IArtistManager is configured named artistManager:
using Spring.Context.Support;
// ...
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
IApplicationContext context = ContextRegistry.GetContext(); // get the application context
IArtistManager mngr = (IArtistManager)context.GetObject("artistManager"); // get the object
return mngr.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Note that this code won't compile either, since rowCount is an instance member, similar to artistManager in your question.
Don't know about spring, but I am sure it has something like structure map.
ObjectFactory.GetInstance<IAristManager>.GetAll();

Resources