繁体   English   中英

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

[英]ASP.NET Calling Server Side Method from Client Side on keypress

简而言之,我需要一种使客户端代码能够在我的项目中触发服务器端方法的方法。 我尝试使用这种功能的方式是,当用户在文本框中输入电子邮件地址时,键入每个字符后,我希望项目触发以下所示的方法,该方法使用一个类来查询数据库。

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 Flask API,Node.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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM