我在aspx页面中有一个文本框。从那里我需要在Json函数中发送文本框的文本因为我在服务器端有一个方法。
[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();
}
在.aspx页面中我有
$('#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;
}
);
现在我的问题是我在数据中发送参数但是我收到一个错误函数运行良好。我已经测试了它没有参数所以它运行良好。所以我发生了一些错误的事情正在传递文本值功能中的文本框。
答案 0 :(得分:3)
您发送的是无效的JSON。替换:
data: "{officename : New}"
使用:
data: "{officename : 'New'}"
甚至更好地使用JSON.stringify
方法,该方法将负责正确编码值:
data: JSON.stringify({ officename : 'New' })
另外,请修复服务器端脚本并使用参数化查询,因为您的代码容易受到SQL注入攻击,如果您将此代码置于野外,您可能会发现自己有一天缺少数据库。哦,你真的不需要任何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();
}
}
}
答案 1 :(得分:0)
替换: 数据:“{officename:New}”
使用:
数据:{officename:'New'},