ASP.NET调用服务器端方法从键盘上的客户端



简单地说,我需要一种使客户端代码能够在项目中触发服务器端方法的方法。我试图使用此类功能的方式是当用户输入其电子邮件地址到文本框中时,每个字符键入我希望该项目触发下面显示的方法,该方法使用类查询我的数据库。

private void EmailCheck()
{
    lblEmailError.Text = null;
    Customer y = new Customer();
    int counter = 0;
    y.Email = Email.Text;
    counter = y.CheckEmail();
    if (counter.Equals(1))
    {
        lblEmailError.Text = "Email is already in use";
    }
    else
    {
        lblEmailError.Text = null;
    }
}

我目前几乎没有JavaScript或任何形式的客户侧脚本的经验。据我了解,Ajax可能在这里对我有用,但是我对如何实施它毫无意义。我也听说过Onkeydown/Press/UP,但我再次不确定如何改变在线解决方案根据我的特定需求。有帮助吗?

最直接的方法是在HTML5中制作按钮,使用jQuery $.ajax()函数调用服务器端REST API(实现可能是C#Web API,Python Blask API,节点。JS API)。

在您的客户端:

<label> Enter something into the textbox </label> 
<input type = "text" id = "myTextBox" placeholder="Enter something"/>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(function(){
//On button click query the server
$("#myTextBox").change(function(){
var textBoxValue = $("#myTextBox).val();
var dataToBeSent = {
 "data": textBoxValue
}; 
$.ajax(function(){
url: "http://localhost:9999/api/YourAPIName",
method: "POST",
data: JSON.stringify(dataToBeSent),
success: function(data){
   console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
   console.log("Failed because" + errorThrown);
}
}); //end .ajax
}); //end click
}); //end jQuery
</script>

在您的服务器端(假设C#):

制作一个模型类,属性与您为[FromBody]属性构建的JSON密钥相同,以正确地进行序列化。

public class SomeModelClass
{
   public string data { get; set; }
}
[HttpPost]
[Route("api/YourAPIName")]
public HttpResponseMessage YourMethod([FromBody] SomeModelClass modelClass)
{
    //perform logic and return a HTTP response
}

相关内容

最新更新