我试图在静态方法中设置asp:SqlDataSource的SeletCommand,但显示了“ System.NullReferenceException:对象引用未设置为对象实例”的错误消息。
namespace TestSPA
{
public partial class editor1 : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static string SelectDataFromSearch(string keyWord)
{
string result = "";
Model.MyDataConnection mdc1 = new Model.MyDataConnection();
OleDbConnection conn1 = new OleDbConnection();
OleDbCommand cmd1 = new OleDbCommand();
conn1.ConnectionString = mdc1.ConnectonString;
cmd1.Connection = conn1;
try
{
conn1.Open();
editor1 ed = new editor1();
//Here is where the error line.
ed.dsWSE.SelectCommand = "SELECT * FROM [News] WHERE [Title] LIKE '%" + keyWord + "%' OR [Intro] LIKE '%" + keyWord + "%' OR [Story] LIKE '%" + keyWord + "%' ORDER BY [DateModified] DESC";
//Here is where the error line.
conn1.Close();
result = keyWord;
}
catch (Exception err)
{
result = err.ToString();
}
return result;
}
}
}
下面是我的jQuery使用Ajax调用上述服务器方法
$("#TxbSearch").on("keyup", function (e) {
e.preventDefault();
var text = $(this).val();
console.info(text);
$.ajax({
type: "POST",
url: "editor.aspx/SelectDataFromSearch",
data: "{'keyWord':'" + text + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (res) {
console.log(res.d);
$("#gvNews").load(location.href + " #gvNews");
},
error: function (xhr, status, error) {
$("#model-error-message").html(error);
$("#ModelError").modal('show')
console.log(error);
}
});
});
#TxbSearch是TextBox的ID,必须在发生“ keyup”事件时将其值传递给服务器方法名称“ SelectDataFromSearch”,然后更新GridView以显示搜索结果。
请帮助。