【问题标题】:Asp.net Webform jquery ajax request not workingAsp.net Webform jquery ajax请求不起作用
【发布时间】:2019-09-13 06:44:18
【问题描述】:

我正在为我的办公室创建一个医院 ERP 项目。我已经添加了一些功能。在这个时候,我的项目需要 jquery ajax 请求。我正在尝试更多,但我在这个网络表单中并不成功。所以我需要帮助专家。 我的代码不起作用 asp.net webform jquery ajax 请求。

这是我的代码

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee GetByEmployeeId(int Id)
{
    Employee employee = new Employee();
    return employee;
}

<script src="Scripts/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#saveButton').click(function () {
            debugger;
            $.ajax({
                type: 'POST',
                url: 'Test.aspx/GetByEmployeeId',
                data: '{Id: ' + 1 + '}',
                success: function (respons) {
                    debugger;
                    alert('ok');
                },
                error: function () {
                    alert('fail')
                }
            })
        })
    })
</script>


  <div class="form-group">
    <asp:Label runat="server" For="nametextBox">Name:</asp:Label>
    <asp:TextBox runat="server" ID="nametextBox" CssClass="form-control"> 
 </asp:TextBox>
</div>

<div class="form-group">
    <button type="submit" class="btn btn-primary" id="saveButton">Save</button>
</div>

我正在尝试,但没有工作

【问题讨论】:

  • 它在哪些方面不适合您?
  • 是的,它不工作
  • GetByEmployeeId 设为static。阅读 here 了解为什么 WebMethod 被标记为静态
  • 我同意@Izzy。使您的 webmethod 静态并传递您需要的字段作为参数。
  • 您还必须在返回对象之前对其进行序列化。

标签: c# jquery asp.net ajax


【解决方案1】:

在您的网络服务中使用静态关键字。

public static Employee GetByEmployeeId(int Id){
Employee employee = new Employee();
return employee;}

【讨论】:

  • 使用静态,这个 jquery 警报消息显示正常,但是这个 cs 文件方法没有命中
【解决方案2】:

在调试器之后使用它,然后测试服务返回的内容以及它们不是您传递的 id=1 上的任何员工。这就是它返回 null 或错误的原因。 var res = JSON.stringify(response); var obj = JSON.parse(res);

【讨论】:

    【解决方案3】:

    首先,让你的方法静态如下:

    public static Employee GetByEmployeeId(int Id)
    

    要使用 ajax 调用方法,您必须将方法设为静态,这是必须的。

    然后将按钮类型从submit 更改为button。 其次使用:

    $('#saveButton').on('click', function () {
    

    代替:

    $('#saveButton').click(function () {
    

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多