简体   繁体   English

ASP.NET和C#中的AJAX问题

[英]AJAX Issue in ASP.NET & C#

I am trying to call a WebMethod in my C# code behind via AJAX .. I have a Bootstrap Modal that needs to display on the click of a linkbutton, also when the link button is pressed, it will fire a WebMethod via AJAX that fills a table in the modal body with a result set from a query. 我试图通过AJAX在我的C#代码后面调用WebMethod 。我有一个Bootstrap Modal,需要在单击linkbutton时显示,同样当按下link按钮时,它也会通过AJAX触发WebMethod来填充一个模态主体中的表,其中包含查询的结果集。

This is the code I have : 这是我的代码:

ASP.NET ASP.NET

<asp:LinkButton href="#viewemydevices" data-toggle="modal" ID="ViewMyDevices" runat="server">
<div class="panel-footer announcement-bottom">
 <div class="row">
      <div class="col-xs-6">
      View Devices
      </div>
      <div class="col-xs-6 text-right">
          <i class="fa fa-arrow-circle-right"></i>
      </div>
 </div>

<div class="modal fade" id="viewemydevices" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h4>This is a section</h4>
        </div>
        <div class="modal-body">
            <table id="MyDevicesTable" class="table tbody" runat="server" visible="false">
                <tbody>
                    <tr>
                        <td>
                            <asp:DataGrid ID="MyDevicesGrid" runat="server" CssClass="table table-striped tbody" Visible="false"
                                AutoGenerateColumns="True"
                                ForeColor="black"
                                HeaderStyle-Font-Bold="true"
                                HeaderStyle-ForeColor="black"
                                GridLines="None"
                                EnableViewState="false"
                                AllowSorting="True"/>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <a class="btn btn-primary" data-dismiss="modal">Close</a>
        </div>

    </div>
</div>

 <script type="text/javascript">

    $.ajax({
        url: 'Default.aspx/ViewMyDevices',
        type: "POST",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            $('#ViewMyDevices').click();
        }
    });

</script>

C# C#

    [WebMethod]
    public void ViewMyDevices()
    {
    string selectMyDevices = "My Query, it works fine";

    sqlCmd = new SqlCommand(selectMyDevices, sqlConn);
    sqlConn.Open();

    SqlDataReader rdrMyDevices = sqlCmd.ExecuteReader();

    //reads row into datagrid
    if (rdrMyDevices.HasRows)
    {
        //sets table/grid to visible
        MyDevicesGrid.Visible = true;
        MyDevicesTable.Visible = true;

        //adds data to grid
        MyDevicesGrid.DataSource = rdrMyDevices;
        MyDevicesGrid.DataBind();
    }
    sqlConn.Close();
}

I do not know what I am missing, the modal is displaying, but no data is displaying. 我不知道自己缺少什么,正在显示模式,但是没有数据在显示。 So I think the AJAX is not being fired... 所以我认为AJAX没有被解雇...

Any suggestions? 有什么建议么?

Based on the cursory look of the code, some extra work needs to be done in order to make this work. 基于代码的粗略外观,需要做一些额外的工作才能完成这项工作。 The steps required that I can see are as follows: 我可以看到的所需步骤如下:

  • Add 'ClientIDMode="static"' attribute to your linkbutton. 将'ClientIDMode =“ static”'属性添加到您的链接按钮。

  • Give ID to the modal body div: 将ID赋予模态主体div:

    <div class="modal-body" id="myContent"> <div class =“ modal-body” id =“ myContent”>

  • The ajax request needs to be bound to the button. ajax请求需要绑定到按钮。 In the original code sample, it was the other way around - the ajax response executed the button click. 在原始代码示例中,这是另一种方法-ajax响应执行了按钮单击。

  • Once the response is received from the server, the HTML content from the response needs to be written to the modal dialog content placeholder like this: '$('#myContent').html(data);'. 一旦从服务器接收到响应,就需要将响应的HTML内容写入模态对话框内容占位符,如下所示:'$('#myContent')。html(data);'。 See the complete JS sample below: 请参阅下面的完整JS示例:

     $('#ViewMyDevices').click( function(){ $.ajax({ url: 'Default.aspx?method=ViewMyDevices', type: "POST", data: '{}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $('#myContent').html(data); } }) }); 
  • The method isn't called automatically for you, as you seem to be using ASP.NET, not MVC. 该方法不会自动为您调用,因为您似乎正在使用ASP.NET,而不是MVC。 You'd need to wire the logic to call it yourself. 您需要连接逻辑以自己调用它。 So, for example you could execute the ajax request with a parameter like this: 'Default.aspx?method=ViewMyDevices'. 因此,例如,您可以使用以下参数执行ajax请求:“ Default.aspx?method = ViewMyDevices”。 Then in the page load event of your aspx page, you'd need to check if the request is of type post and the query parameter matches the method name. 然后,在aspx页面的页面加载事件中,您需要检查请求的类型是否为post,并且查询参数是否与方法名称匹配。 Something like this: 像这样:

     public void Page_Load(object sender, EventArgs e) { if(Request.HttpMethod == "POST" && Request.QueryString["method"] == "ViewMyDevices") { ViewMyDevices(); } } 
  • Then, you'd need to override the Render method of the aspx page and detect if you're making a POST request, in which case only render the desired portion of the page, which is the table: 然后,您需要覆盖aspx页面的Render方法,并检测是否正在发出POST请求,在这种情况下,仅呈现页面的所需部分,即表格:

     protected override void Render(HtmlTextWriter writer) { if(Request.HttpMethod == "POST") { MyDevicesTable.Render(writer); return; } base.Render(writer); } 

This, I believe, should work for you. 我相信这应该对您有用。

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

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