简体   繁体   English

使用jquery / ajax在按钮单击上绑定到gridview

[英]Binding to gridview on button click using jquery/ajax

I have the following aspx controls on my page: 我的页面上有以下aspx控件:

1- GridView: 1- GridView:

<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False">
<Columns>
    <asp:BoundField DataField="StartDate" HeaderText="Date" />
    <asp:BoundField DataField="Title" HeaderText="Event" /> 
    <asp:BoundField DataField="Name" HeaderText="Contact Name" />
    <asp:BoundField DataField="Cell" HeaderText="Contact #" />
    <asp:BoundField DataField="EventType" HeaderText="Type" />
    <asp:BoundField DataField="Confirmed" HeaderText="Status" />
    <asp:BoundField DataField="Comments" HeaderText="Comments" />
</Columns>

2- Text Box ( Start Date ) 2-文本框(开始日期)

<asp:TextBox id="startDate" class="form-control" runat="server"></asp:TextBox>

3- DropDownList ( Event Type ) 3- DropDownList(事件类型)

<asp:DropDownList ID="eventType" class="form-control" runat="server">
    <asp:ListItem Enabled="true" Text="Select Event" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Performance" Value="Performance"></asp:ListItem>
    <asp:ListItem Text="Promotion" Value="Promotion"></asp:ListItem>
    <asp:ListItem Text="Rehersal" Value="Rehersal"></asp:ListItem>
    <asp:ListItem Text="Miscellaneous" Value="Miscellaneous"></asp:ListItem>
</asp:DropDownList>

4- Button ( Filter Events ) 4按钮(过滤事件)

<asp:Button ID="filterEvents" Text="Filter Events" runat="server" />

I want to update the GridView on button click. 我想在单击按钮时更新GridView。 Based on the values of textbox(startDate) and dropdownlist(eventType) a query is made in my WebMethod and called to retrieve data from database. 根据textbox(startDate)和dropdownlist(eventType)的值,在我的WebMethod中进行查询,并调用该查询从数据库中检索数据。

This is my script: 这是我的脚本:

<script type="text/javascript">
    //Add event handler.
    $("body").on("click", "[id*=filterEvents]", function () {
        var startDate = $("[id*=startDate]");
        var eventType = $("[id*=eventType]");
        $.ajax({
            type: "POST",
            url: "ArtistDashboard.aspx/GetEventsWithFilters",
            data: '{str_startDate: "' + startDate.val() + '", str_eventType: "' + eventType.val() + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var xmlDoc = $.parseXML(response.d);
                var xml = $(xmlDoc);
                var customers = xml.find("Table");
                var row = $("[id*=GridView4] tr:last-child").clone(true);
                $("[id*=GridView4] tr").not($("[id*=GridView4] tr:first-child")).remove();
                $.each(customers, function () {
                    var customer = $(this);
                    $("td", row).eq(0).html($(this).find("StartDate").text());
                    $("td", row).eq(1).html($(this).find("Title").text());
                    $("td", row).eq(2).html($(this).find("Name").text());
                    $("td", row).eq(3).html($(this).find("Cell").text());
                    $("td", row).eq(4).html($(this).find("EventType").text());
                    $("td", row).eq(5).html($(this).find("Confirmed").text());
                    $("td", row).eq(6).html($(this).find("Comments").text());
                    $("[id*=GridView4]").append(row);
                    row = $("[id*=GridView4] tr:last-child").clone(true);
                });
            }
        });
    });

</script>

This is my WebMethod: 这是我的WebMethod:

[WebMethod(EnableSession = true)]
    public static string GetEventsWithFilters(string str_startDate, string str_eventType)
    {
        string artId = (string)HttpContext.Current.Session["artID"];
        string query = null;

        if (str_startDate == null && str_eventType == "-1")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'";
        }
        else if (str_startDate == null && str_eventType == "Performance")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND EventType = 'Performance' ";
        }
        else if (str_startDate == null && str_eventType != "Promotion")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND EventType = 'Promotion' ";
        }
        else if (str_startDate == null && str_eventType != "Rehersal")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND EventType = 'Rehersal' ";
        }
        else if (str_startDate != null && str_eventType == "-1")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND StartDate >= '" + str_startDate + "'";
        }
        else if (str_startDate != null && str_eventType == "Performance")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND StartDate >= '" + str_startDate + "'AND EventType = 'Performance' ";
        }
        else if (str_startDate != null && str_eventType == "Promotion")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND StartDate >= '" + str_startDate + "'AND EventType = 'Promotion' ";
        }
        else if (str_startDate != null && str_eventType == "Rehersal")
        {
            query = "SELECT Event.StartDate, Event.Title, Contact.Name, Contact.Cell, Event.EventType, Event.Confirmed, Event.Comments FROM Event INNER JOIN Contact ON Event.ContactID=Contact.ID WHERE ArtistID ='" + artId + "'AND StartDate >= '" + str_startDate + "'AND EventType = 'Rehersal' ";
        }

        SqlCommand cmd = new SqlCommand(query);
        return GetDataWithFilters(cmd).GetXml();
    }

    private static DataSet GetDataWithFilters(SqlCommand cmd)
    {
        string myConnection = @"Data Source=REDDEVIL;Initial Catalog=ArtistManagementSystem;Persist Security Info=True; User ID=sa;Password=fastian123;MultipleActiveResultSets=True;Application Name=EntityFramework";
        using (SqlConnection con = new SqlConnection(myConnection))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;

                }
            }
        }
    }

The problem is that the GridView is not displaying any rows. 问题是GridView没有显示任何行。 What am I doing wrong? 我究竟做错了什么? I know there can be a lot of problems with my code because this is my first time using jQuery/Ajax. 我知道我的代码可能存在很多问题,因为这是我第一次使用jQuery / Ajax。 There are bad programming practices in my code as well, But guys please be generous and point me in the right direction. 我的代码中也有不好的编程习惯,但是伙计们请大方向我指出正确的方向。 I will be really greatful. 我会真的很棒。

In your browser, press F12, go to console window and check for any errors. 在浏览器中,按F12键,进入控制台窗口并检查是否有错误。 jQuery displays all the errors in console window. jQuery在控制台窗口中显示所有错误。 If there is no error, then use console window to check and manipulate JSON response data. 如果没有错误,请使用控制台窗口检查和处理JSON响应数据。

You cannot update your GridView this way. 您不能以这种方式更新GridView The idiomatic way you would handle this in ASP.NET Web Forms is to handle the OnSelectedIndexChanged event on the DropDownList and set AutoPostBack on the DropDownList to true. 你会在ASP.NET Web窗体处理这种情况惯用的办法是处理OnSelectedIndexChanged对事件DropDownList和设置AutoPostBackDropDownList为true。

If you want to update the GridView on the button click, then handle the OnClick event on the button server side. 如果要在单击按钮时更新GridView ,请在按钮服务器端处理OnClick事件。

<asp:Button OnClick="OnClickFilterEvents" ID="filterEvents" Text="Filter Events" runat="server" />

// in code behind:
void OnClickFilterEvents(object sender, EventArgs e)
{
    // update your gridview
}

If you want to do it client side, you are better off not using a GridView at all and rendering an HTML table based on whatever results you get from your WebMethod . 如果要在客户端进行操作,最好不要使用GridView并根据从WebMethod获得的任何结果呈现HTML表。

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

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