使用 Web 服务返回的数据(jQuery、ASP.Net)
我有一个 ASP.Net-Button,单击该按钮时会执行客户端和服务器端代码。 在某些情况下,应该阻止后者的执行。
<asp:LinkButton OnClientClick="if(CheckItems() == false) return false;" runat="server"
ID="Button" onclick="Button_Click">Insert</asp:LinkButton>
CheckItems 方法调用 Web 服务。如果来自 Web 服务的响应是“DataFound”,则 CheckItems 方法应返回 false。
function CheckItems() {
PageMethods.CheckItems($('#<%= txtField.ClientID %>').val(), function(response) {
if (response == "DataFound") {
alert("The text you entered does already exist.");
return false;
}
});
}
使用此代码,CheckItems 不会返回 false。如何才能实现这一目标?
网络方法:
[WebMethod]
public static string CheckItems(string name)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString);
try
{
conn.Open();
var selectCommand = conn.CreateCommand();
selectCommand.CommandText = @"SELECT COUNT(*) FROM [Table] WHERE Name = @Name";
selectCommand.Parameters.Add(new SqlParameter("Name", name));
int results = (int)selectCommand.ExecuteScalar();
if (results > 0)
return "DataFound";
else
return "NoDataFound";
}
finally
{
conn.Close();
}
}
I have an ASP.Net-Button which, when clicked, executes client side and server side code.
Under certain conditions, the execution of the latter should be prevented.
<asp:LinkButton OnClientClick="if(CheckItems() == false) return false;" runat="server"
ID="Button" onclick="Button_Click">Insert</asp:LinkButton>
The method CheckItems calls a web-service. If the response from the web-service is "DataFound", the method CheckItems should return false.
function CheckItems() {
PageMethods.CheckItems($('#<%= txtField.ClientID %>').val(), function(response) {
if (response == "DataFound") {
alert("The text you entered does already exist.");
return false;
}
});
}
With this code, CheckItems does not return false. How can this be achieved?
The web-method:
[WebMethod]
public static string CheckItems(string name)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString);
try
{
conn.Open();
var selectCommand = conn.CreateCommand();
selectCommand.CommandText = @"SELECT COUNT(*) FROM [Table] WHERE Name = @Name";
selectCommand.Parameters.Add(new SqlParameter("Name", name));
int results = (int)selectCommand.ExecuteScalar();
if (results > 0)
return "DataFound";
else
return "NoDataFound";
}
finally
{
conn.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的 JavaScript 函数正在对服务器进行异步调用,因此它无法立即将结果返回给您的单击事件。您需要将您的内容分离到单独的 JavaScript 函数中,例如:
Since your javascript function is making an asynchronous call to the server, it cannot return the result immediately to your click event. You'll need to separate out your stuff into separate javascript functions, like: