Jquery separate list items AJAX - asp.net

public class searchResult
{
public int id;
public string name;
}
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.GenerateScriptType(typeof(searchResult))]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public searchResult[] Search(int txtSearch)
{
//Semuler to slow internet connection
System.Threading.Thread.Sleep(2000);
//Declare collection of searchResult
List<searchResult> resultList = new List<searchResult>();
DataSet ds = Classes.getEmployeeDetailSet("SELECT [Employee ID],[First Name] FROM [Employee$] WHERE [Employee ID] like '" + txtSearch + "%'");
DataTable dt = new DataTable();
dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
searchResult result = new searchResult();
result.id = int.Parse(dt.Rows[0]["Employee ID"].ToString());
result.name = dt.Rows[0]["First Name"].ToString();
resultList.Add(result);
}
return resultList.ToArray();
}
i have created a list like
List<searchResult> resultList = new List<searchResult>(); this
and i have return that list
to call this i have use ajax code like this
$.ajax({ type: "POST",
url: "WebService1.asmx/Search", //function that in web service
data: "{txtSearch:" + $("#txtSearch").val() + "}", // passing value of txtSearch input
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var result = response.d;
var value = '';
$.each(result, function(index, res) {
value = value + res.id + res.name;
});
alert(value);
alert("Record was updated successfully,,");
},
error: function(msg) {
alert("Error while calling web service,,");
}
});
My problem is that I am getting only one element from the database
I think I am not able to separate the list in the ajax response here
$.each(result, function(index, res) {
value = value + res.id + res.name;
});
I want to create a array with use of this id+name
please help

As Robert Slaney said, you are only returning the first result from the database.
Try something like this on the server side.
public class SearchResult
{
public int ID;
public string Name;
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod, ScriptMethod]
public SearchResult[] Search(int employeeID)
{
List<SearchResult> resultList = new List<searchResult>();
DataSet ds = Classes.getEmployeeDetailSet("SELECT [Employee ID],[First Name] FROM [Employee$] WHERE [Employee ID] like '" + employeeID + "%'");
DataTable dt = ds.Tables[0];
foreach(DataRow row in dt.Rows)
{
resultList.Add(new SearchResult{ ID = int.Parse(row["Employee ID"].ToString()), Name = row["First Name"].ToString()});
}
return resultList.ToArray();
}
}
You can also use Chrome Developer Tools to inspect your request and response and verify that the data is actually being returned.

Related

How to send data using Json and get in asp.net services

I am php developer and recently switched to asp, I want to send data to web services and get there but I am unable to come up with a solution.
In php if you want to access data for back-end process purpose we simply use
.Serialize(); method,
for example:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
and in Jscript function we will serialize the form, e.g:
var data = $("#loginForm").serialize();
and in process side I can call it by inputs name, But in asp.net I am unable to do the same, I might be missing something or does asp.net do not support such approach at all? I do not know please programmers help me out.
You should use Id property and use stingify() method instead of serialization.
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
Now create a class and create two public variables and call both variables by creating class object in web service class.
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= #m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("#m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
HTML+JS+ WEB-SERVICE
JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
WEB-SERVICE
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
On Codebehind(.cs):
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
I have assumed that you are working on webforms.
you must used jsonp in asp
$.ajax({
url: 'you path',
datatype: 'jsonp',
data: {....}
});

Convert data to JSON format

i have used the Newtonsoft.Json for converting data into json format.
I have write the below code:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
string JSONString = string.Empty;
JSONString = "{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}";
return JSONString;
}
So it gives me the below output:
But i want the output like :
{"mydata":[{"id":125},{"id":137},{"id":249},{"id":201},{"id":124},
{"id":173},{"id":160},{"id":153},{"id":146},{"id":168}]}
So how can i convert to it from xml to json. ?
I run your solution in a console application and I can clearly see the problem. If you avoid building json manually, the problem will go away. As I don't have database, I have added my data rows manually. Hope that will help.
using Newtonsoft.Json;
using System;
using System.Data;
namespace Test
{
class MyDataContainer
{
public DataTable mydata { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write(DataTableToJSONWithJSONNet());
Console.Read();
}
static string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
dt.Rows.Add(1);
dt.Rows.Add(2);
MyDataContainer cont = new MyDataContainer();
cont.mydata = dt;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(cont);
//to see your attempt uncomment the blow lines
//Console.Write("{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}");
//Console.WriteLine();
return JSONString;
}
}
}
Looking into your codes, you are already declared that your output is type of JSON, so on the response data it will return a JSON string.
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
And you also declared that this is a ScriptMethod. My thought is you are testing your app by running your code and accessing the url of the web service - for example http://localhost/test.asmx and clicking the invoke button on your DataTableToJSONWithJSONNet method. This approach will really display JSON result enclosed on XML format. The best way to test your own code is to invoke the web service using something like jQuery Ajax or equivalent (client scripts).
You can change your code to something like this to achieve the output you are looking for:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyResponse DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
MyResponse result = new MyResponse();
result.mydata = dt;
return result;
}
class MyResponse
{
private object _mydata;
public object mydata { get { return this._mydata; } set { this._mydata = value; } }
public MyResponse() { }
}

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.

Need to change the format of data return from JSON

I'm creating a webservice which should get data from database(sql server) and return it.
Every thing working fine. But what I need is I need to display the data with the format which I needed.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
// public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT * FROM Contact e WHERE FirstName LIKE '%" + SearchTerm + "%'";
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(ds);
con.Close();
// Create a multidimensional array
string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in ds.Tables[0].Rows)
{
//EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Contactno"].ToString() };
EmpArray[i] = new string[] { "FNAME: " + rs["FirstName"].ToString(), "LName: " + rs["LastName"].ToString(), "Contactno: " + rs["Contactno"].ToString()};
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(EmpArray);
return strJSON;
}
catch (Exception ex) { return errmsg(ex); }
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Here is my output:
[["FNAME: devi","LName: priya ","Contactno: 965577796 "],
["FNAME: arun","LName: kumar ","Contactno: 9944142109"],
["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]
But I need the result in the following format:(which should contain curly braces and the word cargo at starting each name and value should start and end with double codes..
{ "Cargo": [ { "FNAME": "devi", "LName": "priya " },
{"FNAME": "arun", "LName": "kumar" }, { "FNAME": "karu ", "LName": "ronald" }] }
The followiing code solves my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ToolboxItem(false)]
public class CService : System.Web.Services.WebService
{
public CService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void CargoNet()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT TOP 1 * FROM cargo_tracking ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}

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.

Resources