我正在开发一个webform,它当前在Text Change事件上有一个触发器:
protected void txtBox1_TextChanged(object sender, EventArgs e)
{
Validate();
}
我遇到的问题是,只有当用户在框中输入文字并且焦点丢失时才会触发。
我遇到问题的具体方案是:
答案 0 :(得分:0)
这可以在你的.aspx页面上找到:
<asp:TextBox runat="server" ClientIdMode="static" id="txtBox1">
<script type="text/javascript">
$("#txtBox1").on('input propertychange paste', function(){
$.ajax({
type: "POST",
url: "api/MyValidator/ValidateTextBox?text=" + $("#txtBox1").val()
}) //close AJAX call
.done(function (resp){
if(!resp.Valid) {alert('Not valid: ' + resp.msg);}
}); //close Done handler
}); //close change handler
</script>
这是Web API函数,它将检查数据库并回复AJAX请求。
public ValidationResponse ValidateTextBox(string text)
{
//check your database. If it's good, set valid to true, otherwise false. If not valid, then set reason to the reason why it's not valid.
bool valid;
string reason;
//construct response
var response = new ValidationResponse(){ Valid = valid, msg = reason};
//return response
return response;
}
另外,将这个课程放在某个地方:
public class ValidationResponse
{
public bool Valid {get; set;}
public string msg {get; set;}
}
我们使用How to detect a textbox's content has changed提供的示例来检测文本框值何时更改。当它发生变化时,我们使用jQuery对我们的AJAX进行Web API调用,在那里我们返回一个响应,表明它已通过验证或验证失败。然后我们使用.done()
中的客户端代码来检查来自Web API的响应,并在失败时显示验证失败的消息。
我知道这看起来像检查单个文本框的代码很多。但是通过一些操作,您可以通过单个AJAX调用验证整个表单,并且它不会比我们现在拥有的代码多得多。
注意,我故意省略了一些基本的Web API配置,因为在单个答案中需要讨论很多。我的意图不是给你一个即插即用的#34;回答,而是向您展示一旦您学会了AJAX和Web API的基础知识,使用优秀的架构是多么容易。