Arraylist and webmethod - asp.net

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']);
})
}

Related

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

Binding Lable from webmethod using ajax

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.

Getting [object Object] error when call JQuery Ajax function for Json data

I'm getting the following error when try to read json data from asp.net function, here is the image error
Here is the jQuery code,
<script type="text/javascript">
$(document).ready(function () {
$("#getdata").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
// $("#company").html(data.d);
console.log(data);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
what wrong I did to get this error. Appreciate your any help.
getting this error from console log,console.log(error)
The reason you are seeing that is that data.d is an object representing the returned JSON text response. When you pass in an object into alert, it displays [object Object]. Whatever you are looking for will be a property of data.d. I would put a breakpoint on that line and see what properties are available. It'll be something like data.d.myProperty which will contain the actual string / HTML you are trying to work with.
dont use alert! That will show this only.
Since your response is a Json Object, please try to JSON.stringify it or use console.log to view the data
Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the asp.net function. For example,
[WebMethod()]
public static string GetData()
{
try
{
string strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}
This answer not for experts only for just beginners, thank you.

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.

How can i see datatable which is the return from a webservice method

I am trying use a datatable from a web service method. I can see return value when it's a string data.
This my code and it returns an alert hatada : null
$.ajax(
{
type: 'POST',
url: 'http://localhost:40764/HastaTahlilUyariServisi.asmx/Hello',
data: "{_sTcKimlikNo: '111111111111', _iKlinikKodu:121212, _bAy:12, _iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(ajaxCevap) {
alert('basarili: ' + ajaxCevap); //$('#dv').html(ajaxCevap.d);
},
error: function(xhr, status) {
alert("hatada:" + xhr.responseXML);
},
beforeSend: function() {
alert('gonderilecek');
},
afterSend: function() {
alert('gonderildi');
},
complete: function(xhr, status) {
if (status == 'success')
alert('success' + $.httpData(xhr));
}
}
and this is my webservice method:
[WebMethod]
public DataTable Hello(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
DataTable dt = new DataTable();
dt.Columns.Add("ad");
DataRow rw = dt.NewRow();
rw[0] = _sTcKimlikNo + " " + _iKlinikKodu + " " + _bAy + " " + _iYil;
return dt;
}
How can i see datatable from webservice method?
Thanks in advance.
No Serialization problem, just name your datatable and that will solve the problem.
public DataTable LineChrt() {
string query = "select m.class,sum(m.plannedvisits)" +
"plannedvisits,sum(m.actualvisits) actualvisits from vw_MTD_TgtVsAct_Calls1 m " +
"where 1=1 and m.class in ('A','B','C') and m.month = 6 " +
"group by m.class";
string constr = System.Configuration
.ConfigurationSettings.AppSettings["PocketDCR"];
DataTable data = new DataTable();
SqlDataAdapter LCData = new SqlDataAdapter(query,constr);
LCData.Fill(data);
data.TableName = "ChartData";
return data;
}
I don't think you can return a DataTable from a web service due to serialisation problems. This Microsoft article suggests returning a DataSet instead:
Problems using an XML Web service that returns a DataTable

Resources