Binding Lable from webmethod using ajax - asp.net

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};

You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

Related

Unknown web method When Making AJAX Call to WebMethod with ASP.NET

I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
email = $("#txtEmailAddress").val();
password = $("#txtPassword").val();
//Create the login info object
var loginInfo = {};
//Set the object properties and value
loginInfo.Email = email;
loginInfo.Password = password;
//Make the ajax call
$.ajax({
type: "POST",
dataType: 'json',
url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
data: '{loginInfo:' + JSON.stringify(loginInfo) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d == null || data.d == undefined)
{
alert("Username or password not correct = " + data.d);
console.log(data);
console.log(loginInfo);
console.log(this.url);
}
},
error: function (data) {
console.log(data);
console.log(loginInfo);
console.log(this.url);
alert(data.d);
}
});
});
And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
//Variable to hold the user email address
String email = string.Empty;
//Get the connection string from config file
String connectionString = iDbConfiguration.GetConnectionString();
//Create the command text
String commandText = "select Email, Password from VUser where Email = #Email & Password = #Password";
//Create database connection object and open it
using(SqlConnection loginConnection = new SqlConnection(connectionString))
{
//Set command paramters
SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
//Set command type to text
loginCommand.CommandType = System.Data.CommandType.Text;
//Add parameter to command
loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
loginCommand.Parameters.AddWithValue("#Password", loginInfo.Password);
//Open the database connection
try
{
loginConnection.Open();
SqlDataReader loginReader = loginCommand.ExecuteReader();
if(loginReader.HasRows)
{
HttpContext.Current.Response.Write(loginReader.ToString());
while (loginReader.Read())
{
if (loginReader.HasRows)
{
email = loginReader["Email"].ToString();
}
}
}
}
catch(SqlException sqlEx)
{
HttpContext.Current.Response.Write(sqlEx.Message);
}
finally
{
loginConnection.Close();
}
}
return email;
}

ASP.NET: Relative Path with Root Operator('~') in Client side

I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}

Error in inserting data with JSON and Ajax

I don't know where the problem is, my code looks fine and I tried hard, but getting error all the time.
Here is my code:
Markup:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function(){
var Name=document.getElementById('Text1').value
var Class=document.getElementById('Text2').value
var Data=JSON.stringify({Name:Name,Class:Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function () {
alert("Error")
}
});
});
});
</script>
ASP.NET AJAX Page Method in code-behind:
[WebMethod]
public string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
Try this:
Method must be static if it is in aspx page code behind
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
You don't need to stringify it.
Without stringifying just pass
"{'Name':'"+Name+"','Class':'"+Class+"'}"
If you want to pass the stringified object it must be as shown below
JSON.stringify({'Name':Name,'Class':Class});
See the Quotes added.
var Data=JSON.stringify({'Name':Name,'Class':Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function ()
{ alert("Error") }
});
And in the page back code
[WebMethod]
public string InsertData(myobj getdat)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", getdat.Name);
cmd.Parameters.AddWithValue("#Classs",getdat.Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
public class myobj
{
public string Name {get;set;}
public string Class{get;set;}
}
ASP.NET AJAX Page Methods must be static, change your code to this:
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
Read Why do ASP.NET AJAX page methods have to be static? for an explanation as to why.

accessing data using ajax page methods directly

I want to access data and show in label ajax page methods but data is not displaying.
PageMethods.GetDataFromDB(OnSucceeded, OnFailed);
//}
function OnSucceeded(result, userContext, methodName) {
var jsonData = eval(result.d);
$get('Label1').innerHTML = jsonData.FirstName;
}
[WebMethod]
public static string GetDataFromDB()
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName",dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
table has only one row.
Since you have given the tags as jQuery and jQuery Ajax I am deviating a little from the solution.
Do these things
1.Wrap your WebMethod in a try-catch block. try-catch are there for a reason.
[WebMethod]
public static string GetDataFromDB()
{
try
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName", dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
throw new Exception(exception.Message);
}
}
Please note that this Dictionary will fail with Duplicate Key error if you have more than one row. If there are no errors lets move to step 2.
2.Do not use PageMethods.GetDataFromDB. It very ancient. Using jQuery one can consume ASP.NET Ajax Page Methods directly. Call Page method like this.
function LoadNames() {
$.ajax({
contentType: "application/json;",
data: "{}",
type: "POST",
url: 'Test1.aspx/GetDataFromDB',
success: function (msg) {
OnSucceeded(msg);
},
error: function (xhr, status, error) {
//alert("error");
//OnFailed(a, b, c);
}
});
}
function OnSucceeded(dict) {
var jsonData = dict.hasOwnProperty("d") ? dict.d : dict;
var json = $.parseJSON(jsonData);
alert(json.FirstName);
}
Also, don't eval(result.d) when we have $.parseJSON in jQuery.
Hope this helps.

Arraylist and webmethod

I have written a web method in ASP.net which it's output is an ArrayList of cities that is read from Sql server database.
this webmethod is called using Jquery in clientside.
but I don't know how to read each item of array list using jquery. for example every city and it's id equivalent.
Below is my Webmethod:
public ArrayList showcity(int s)
{
ArrayList list = new ArrayList();
String strConnString = ConfigurationManager
.ConnectionStrings["ConnectionCS"].ConnectionString;
String strQuery = "select ID, City from tbl_city where stateid=#s";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#s", s);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(
sdr["City"].ToString(),
sdr["ID"].ToString()
));
}
con.Close();
return list;
}
}
and this is my clientside code:
function showcity() {
$.ajax(
{ url: "../AjaxServices/StateCity.asmx/showcity",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: '{s: ' + $('#<%=DpState.ClientID%>').val() + '}',
success: function(data) {
***// what should I write here to access every item separately***
},
error: function() { alert("Error"); }
})
}
If I use alert(data.d) I will get [object][object][object][object],.....
You need to create an actual type and return an array of that type. So create a City class, mark it serializable, build a List<City> in your loop, then return .ToArray(). The return type of your web method should be City[]
Instead of ArrayList being returned, it would be better to return an array with two dimension.
I found a solution myself so I share it here, just be careful about Value and Text they're case sensitive
success: function(data) {
$.each(data.d, function() {
alert(this['Value'] + ':' + this['Text']);
})
}

Resources