I am new in JQuery and API, here i am trying to retrieve data from SQL in JSON format and then bind it to table. Data is returned here return details.ToString(); when I debug but it does not bind data into table. Any Error here?
Controller:
public class EmployeeController : ApiController
{
static EmpRepository repository = new EmpRepository();
public string GetData(Employee Em) {
var re = repository.GetData(Em);
return re;
}
}
Repository Class:
public string GetData(Employee Em)
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
//user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details.ToString();
}
JQuery:
$(document).ready(function DisplayResult() {
var Emp = {};
var url = 'api/Employee/GetData';
$.ajax({
type: "POST",
url: url,
contentType: "application/json;charset=utf-8",
//data: {},
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].LastName + "</td><td>" + data.d[i].Company + "</td></tr>");
}
},
error: function (result) {
alert("error");
}
});
});
Here are the changes you need to do each section.
First in your Repository just return the details as is not details.ToString()
Next in both your repository class as well as in WebApi controller you don't need to Employee parameter you are not using it anywhere. Remove it.
Repository Class ->
public string GetData()
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
// user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details;
}
WebApi Controller :
You don't need to convert anything to JSON here, by default JSON.NET serializer will convert your List to JSON Array of Employee Objects.
public class EmployeeController : ApiController
{
static EmpRepository repository = new EmpRepository();
public string GetData() {
var re = repository.GetData();
return re;
}
}
Now in your jquery :
Ideally you are doing a 'GET' here not a POST , data returned now is an array of employee objects iterate through it.
$(document).ready(function DisplayResult() {
var Emp = {};
var url = 'api/Employee/GetData';
$.ajax({
type: "GET",
url: url,
contentType: "application/json;charset=utf-8",
success: function (data) {
for (var i = 0; i < data.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data[i].FirstName + "</td><td>" + data[i].LastName + "</td><td>" + data[i].Company + "</td></tr>");
}
},
error: function (result) {
alert("error");
}
});
});
I think you have two mistakes in your code.
On "public string GetData(Employee Em) "
I think that you want to return list of Employee
so should change return details.ToString(); toreturn details;`
It will be
public List<Employee> GetData(Employee Em)
{
DataTable dt = new DataTable();
List<Employee> details = new List<Employee>();
connection();
com = new SqlCommand("select FirstName, LastName, Company from Employee", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Employee user = new Employee();
// user.Id = Int32.Parse(string dr["Id"]);
user.FirstName = dr["FirstName"].ToString();
user.LastName = dr["LastName"].ToString();
user.Company = dr["Company"].ToString();
details.Add(user);
}
return details; }
-Change GetData api, must return JSON format. It will be as below
public string GetData(Employee Em) {
var re = repository.GetData(Em);
return Json(re);}
and
for (var i = 0; i < data.d.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].LastName + "</td><td>" + data.d[i].Company + "</td></tr>");
}
change to
for (var i = 0; i < data.length; i++)
{
$("#tbDetails").appendTo("<tr><td>" + data[i].FirstName + "</td><td>" + data[i].LastName + "</td><td>" + data[i].Company + "</td></tr>");
}
Good luck!
Related
I use below code .I have 2 dropdownlist it work fine.but problem is second drodownlist value doesnt store in database when i click on update button.It gives null value reference unhandled error.On form.aspx.cs i take that value on label cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString()); but in this it takes null value
<script type="text/javascript">
$(function() {
//$('#<%=DropDownList2.ClientID %>').attr('disabled', 'disabled');
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$('#<%=DropDownList1.ClientID %>').change(function() {
var country = $('#<%=DropDownList1.ClientID%>').val()
$('#<%=DropDownList2.ClientID %>').removeAttr("disabled");
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'country':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
},
error: function(data) {
alert('Something Went Wrong')
}
});
});
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$("#DropDownList2").children("option").is("selected").text()
$('#<%=DropDownList2.ClientID %>').change(function() {
var stateid = $('#<%=DropDownList2.ClientID%>').val()
var myVar =('#DropDownList2').find(':selected').text();
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'state':'" + post_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
$("option:selected", myVar).text()
},
error: function(data) {
alert('Something Went Wrong')
}
});
})
})
</script>
and my c# code is
private void Bindcategorydown()
{
String strQuery = "SELECT [dept_no],[department_name] FROM [first].[dbo].[dept_add]";
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "department_name";
DropDownList1.DataValueField = "dept_no";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Department", "0"));
con.Close();
}
}
}
[WebMethod]
public static string BindPosts(string country)
{
StringWriter builder = new StringWriter();
String strQuery = "SELECT [post_id],[post_name] FROM [first].[dbo].[add_post] where group_id=#dept_no";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("#dept_no", country);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["post_name"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["post_id"] + "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}
and on update button i use this
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.Text);
If the problem persists, send us the stack trace of the error.
I am trying to pass a list that is populated by the database in a Web Service to ajax using JSON. However, I'm not sure what I'm missing and where to go from here.
Web Service
public class RetrieveWidgets : System.Web.Services.WebService
{
[WebMethod]
public static RetrieveWidgetsDAL[] GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> GetWidgetList = new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
GetWidgetList.Add(widgetDAL);
}
}
//trying to serialize GetWidgetList to JSON
var js = new JavaScriptSerializer();
var strJSON = js.Serialize(GetWidgetList);// not sure if this is the correct way?
}
conn.Close();
return GetWidgetList.ToArray();
}
}
Data Structure class
public class RetrieveWidgetsDAL
{
public string Title { get; set; }
public int SortNo { get; set; }
public int Collapsed { get; set; }
public int ColumnId { get; set; }
}
ajax
$(document).ready(function () {
if ($.cookie('modal_shown') == null) {
$.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
$('#popup').dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
data: <---don't know how to get the data,
dataType: "json",
success: function (response) {
alert(data);
}
});
}
});
I'm new to the idea of JSON so I'm still struggling to learn it. Any help is greatly appreciated.
EDIT: This is what I receive now on error in the browser console..
EDIT 2: I've removed static from my webservice..
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<RetrieveWidgetsDAL> GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> lstData = new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
lstData.Add(widgetDAL);
}
}
}
conn.Close();
return lstData;
}
Now my console shows [object Object]
Edit 3: I used the solution that has the accepted answer, however.. had to fix the ajax..
contentType was missing a ;
contentType: "application/json; charset=utf-8"
and now it alerts on the success!
Try this
[WebMethod]
public static List<RetrieveWidgetsDAL> GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> lstData= new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
lstData.Add(widgetDAL);
}
}
}
conn.Close();
return lstData;
}
}
JS: On success use response.d
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
dataType: "json",
success: function (response) {
alert(response.d); // try using response.d
},
error:function (repo){
console.log(repo);
}
});
First of all, you need to change your webserver return:
public class RetrieveWidgets : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static RetrieveWidgetsDAL[] GetWidgets()
{
//...
}
}
Then change your jquery:
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
cache: false,
dataType: "json"
})
.done(function( data ) {
alert(data);
});
Im trying to use a asp.net webservice to send JSON data, which it gets from a MySql database, to a web app, which uses jQuery to display the data sent through JSON.
My webservice method looks like this:
[WebMethod(Description = "yet another test .....")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCustomerByIDTRY()
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["my_domain_mysql"].ConnectionString;
MySqlConnection connection1 = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand("SELECT Vet_Users.FirstName, Vet_Users.LastName, Vet_Users.UserID, Vet_Customer.CusID FROM Vet_Users JOIN Vet_Customer ON Vet_Users.UserID=Vet_Customer.UserID");
DataSet CusIDDataSet = new DataSet();
MySqlDataAdapter CusIDDataAdapter = new MySqlDataAdapter(cmd);
CusIDDataAdapter.SelectCommand.Connection = connection1;
CusIDDataAdapter.Fill(CusIDDataSet, "reading");
connection1.Close();
StringBuilder JSON = new StringBuilder();
JSON.Append("{");
JSON.Append("\"NumberOfCustomers\":\"" + CusIDDataSet.Tables[0].Rows.Count.ToString() + "\", ");
JSON.Append("\"Customer\":[");
foreach (DataRow rs in CusIDDataSet.Tables[0].Rows)
{
JSON.Append("{");
JSON.Append("\"CusID\":\"" + rs["CusID"].ToString() + "\",");
JSON.Append("\"FirstName\":\"" + rs["FirstName"].ToString() + "\",");
JSON.Append("\"LastName\":\"" + rs["LastName"].ToString() + "\",");
if (JSON.ToString().EndsWith(","))
JSON = JSON.Remove(JSON.Length - 1, 1);
JSON.Append("},");
}
if (JSON.ToString().EndsWith(","))
JSON = JSON.Remove(JSON.Length - 1, 1);
JSON.Append("]}");
return JSON.ToString();
}
The JSON comes back like this:
Object { d="{"NumberOfCustomers":"1...","LastName":"Woods"}]}"}
Its wrapped in a "d", cause of asp.net 3.5+ security issue.
(http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/)
But my JSON comes wrapped in double quotes, and i can't figure out why.
"{"NumberOfCustomers":"15", "Customer":[{"CusID":"1","FirstName":"Ina","LastName":"Williamson"},{"CusID":"2","FirstName":"Hyacinth","LastName":"Brady"},{"CusID":"3","FirstName":"Coby","LastName":"Shannon"}]}"
This is the jQuery function, that im trying to get working:
function FinalTest() {
$.ajax({
type: "POST",
url: "url",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(eval(data.d.NumberOfCustomers));
}
});
};
Don't manually serialize JSON. The framework will handle that for you. More info here: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
Do something like this and JavaScriptSerializer will handle building valid JSON for you:
public class Customer {
public string CusID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
[WebMethod(Description = "yet another test .....")]
[ScriptMethod]
public object GetCustomerByIDTRY() {
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["my_domain_mysql"].ConnectionString;
MySqlConnection connection1 = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand("SELECT Vet_Users.FirstName, Vet_Users.LastName, Vet_Users.UserID, Vet_Customer.CusID FROM Vet_Users JOIN Vet_Customer ON Vet_Users.UserID=Vet_Customer.UserID");
DataSet CusIDDataSet = new DataSet();
MySqlDataAdapter CusIDDataAdapter = new MySqlDataAdapter(cmd);
CusIDDataAdapter.SelectCommand.Connection = connection1;
CusIDDataAdapter.Fill(CusIDDataSet, "reading");
connection1.Close();
var customers = new List<Customer>();
foreach (DataRow rs in CusIDDataSet.Tables[0].Rows) {
customers.Add(new Customer {
CusID = rs["CusID"].ToString(),
FirstName = rs["FirstName"].ToString(),
LastName = rs["LastName"].ToString()
});
}
return new {
NumberOfCustomers = CusIDDataSet.Tables[0].Rows.Count.ToString(),
Customer = customers
};
}
Here I have two dropdownlists. First one to display the list of countries and the second to list the states value for selected country from first. The list of values are populated from
properly but in the dropdownlist, the values are not populated.
jQuery:
$(document).ready(function () {
$("#Country").change(function () {
var Id = $('#Country option:selected').attr('value');
$("#Region").empty();
$.getJSON("/ControllerName/GetRegionList",{ ID: Id },
function (data) {
jQuery.each(data, function (key) {
$("#Region").append($("<option></option>").val(ID).html(Name));
});
});
});
});
View :
#Html.DropDownList("Country", new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue))
#Html.DropDownList("Region", new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
Controller:
public List<Region> GetRegionList(int ID)
{
int countryid = ID;
AddressModel objmodel = new AddressModel();
List<Region> objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
countryid = Convert.ToInt32(ID);
SqlCommand cmd = new SqlCommand("USP_ProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region { ID = dr["RegionId"].ToString(), Name = dr["Name"].ToString() });
}
}
dr.Close();
con.Close();
}
return objRegionList;
}
What is the mistake in my code.? Any Suggestions.
EDIT : Added the snapshot
In ASP.NET MVC controller actions must return ActionResults. In your case you could return JSON:
public ActionResult GetRegionList(int id)
{
var objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
int countryid = ID;
using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE"))
using (var cmd = conn.CreateCommand())
{
con.Open();
cmd.CommandText = "USP_ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region
{
ID = dr["RegionId"].ToString(),
Name = dr["Name"].ToString()
});
}
}
}
}
}
return Json(objRegionList, JsonRequestBehavior.AllowGet);
}
Notice that I have also cleared your code from unused variables and unnecessary Convert.ToInt32 calls and most importantly wrapped IDisaposable resources such as SQL connections, commands and data readers in using statements to avoid leaking resources.
Then include the url of the controller action as a data-* attribute on the first dropdown to avoid ugly hardcoding it in your javascript and breaking when you deploy your application in IIS in a virtual directory:
#Html.DropDownList(
"Country",
new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue),
new { data_url = Url.Action("GetRegionList", "ControllerName") }
)
finally adapt (simplify) your javascript:
$('#Country').change(function () {
var regionDdl = $('#Region');
regionDdl.empty();
var id = $(this).val();
var url = $(this).data(url);
$.getJSON(url, { id: id }, function (data) {
$.each(data, function (index, region) {
regionDdl.append(
$('<option/>', {
value: region.ID,
html: region.Name
})
);
});
});
});
I have a text box in aspx page. from that i need to send the text of the textbox in function in Json For that i have a method in server side.
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
DataTable dt = new DataTable();
List<OfficeDetails> details = new List<OfficeDetails>();
using (SqlConnection con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select OfficeName,City,Country from Office where OfficeName like '%" + officename + "%'", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
OfficeDetails Office = new OfficeDetails();
Office.OfficeName = dtrow["OfficeName"].ToString();
Office.City = dtrow["City"].ToString();
Office.Country = dtrow["Country"].ToString();
details.Add(Office);
}
}
}
return details.ToArray();
}
and in .aspx page I have
$('#btnSearch').click
(
function () {
var searchtext = $("#txtSearch").val();
alert(searchtext);
$.ajax(
{
type: "POST",
url: "Gridview.aspx/BindSearchDatatable",
data: "{officename : New}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
}
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}
);
return false;
}
);
Now my Question is I send the Parameter in data but i am getting an error The function is running well.I have tested it without parameter so its running well.so i thing some wrong things is going on passing the text value Of textbox in function.
You are sending an invalid JSON. Replace:
data: "{officename : New}"
with:
data: "{officename : 'New'}"
or even better use the JSON.stringify method which wil take care of properly encoding the values:
data: JSON.stringify({ officename : 'New' })
Also please fix your server side script and use parametrized queries because your code is vulnerable to SQL injection attacks and if you put this code into the wild, you might find yourself one day with a missing database. Oh and you really don't need any DataTables:
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
using (var con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT OfficeName, City, Country FROM Office WHERE OfficeName LIKE #officename";
cmd.Parameters.AddWithValue("#officename", "%" + officename + "%");
using (var reader = cmd.ExecuteReader())
{
var details = new List<OfficeDetails>();
while (reader.Read())
{
var office = new OfficeDetails();
office.OfficeName = reader.GetString(reader.GetOrdinal("OfficeName"));
office.City = reader.GetString(reader.GetOrdinal("City"));
office.Country = reader.GetString(reader.GetOrdinal("Country"));
details.Add(office);
}
return details.ToArray();
}
}
}
Replace:
data: "{officename : New}"
with:
data: {officename : 'New'},