如何在 codeBehind ASP.net C# 中添加 jquery .trigger()

How to Add jquery .trigger() in codeBehind ASP.net C#

我需要在生成 Gridview 后自动点击隐藏按钮,我有:

$("#<%=btnExcel.ClientID%>").trigger("click");

工作完美,但我需要在生成 Gridview 后将其添加到代码隐藏,我尝试添加一个函数,然后在 OnRowdatabound 事件中调用它:

//I tried creating a function
<script type="text/javascript">
    function Excel() {
        $("#<%=btnExcel.ClientID%>").trigger("click");
    }
</script>

所有CS代码

public partial class ReportesCasos : System.Web.UI.Page
{
    string BaseX = "SELECT DISTINCT Casos.Cliente AS idCliente, Casos.Asignado AS Usuario, Casos.idCaso AS 'N° Caso', Clientes.nombre AS Cliente,Asunto, Estado.Descripcion AS 'Estado Actual', Causa.Descripcion AS Causa_Raiz, Usuarios.Login AS 'Tecnico_Asignado', Zona.Descripcion AS 'Zona', Sector.Sector AS 'Sector', Usuarios.Login AS 'Asignado', CONVERT (nchar, Casos.Reportado, " + funciones.Fecha() + ") AS Reportado, CONVERT (nchar, Casos.Cerrado, " + funciones.Fecha() + ") AS Cerrado, CONVERT (nchar, Casos.Vencimiento, " + funciones.Fecha() + ") AS Vencimiento,fecha, CONVERT(nchar,fecha," + funciones.Fecha() + ") As Fecha2, TipoCaso.Descripcion AS TipoCaso, Prioridad.Descripcion AS Prioridad, Casos.Horas AS HorasTrabajadas, Casos.Atendidos AS EquiposAtendidos, Casos.Contrato AS BajoContrato, Casos.Valoracion AS Evaluacion, Casos.Facturado AS facturado, Casos.Factura AS 'N° Factura', Casos.Contacto AS ContactoCliente, Casos.Diagnostico AS Diagnostico, Casos.Solucion AS Solucion FROM Casos INNER JOIN TipoCaso ON Casos.TipoCaso = TipoCaso.idTipo INNER JOIN Prioridad ON Casos.Prioridad = Prioridad.idPrioridad INNER JOIN Estado ON Casos.Estado = Estado.idEstado INNER JOIN Usuarios ON Casos.Asignado = Usuarios.idUsuario INNER JOIN clientes ON idCliente = Casos.Cliente INNER JOIN (SELECT Caso,MAX(Fecha)AS Fecha FROM HistorialEstado";
    string BaseX1 = " GROUP BY Caso) AS HistorialEstado ON Caso = idCaso INNER JOIN Zona ON Casos.Zona = Zona.idZona INNER JOIN Sector ON Casos.Sector = Sector.idSector INNER JOIN Causa ON Casos.Causa = Causa.idCausa WHERE tipocaso <> 5 AND ";
    string ColaX2 = " ORDER BY idCaso";
    string ClienteX = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["Usuario"] == null || Session["Sesion"] == null || !funciones.ChequearUsuario(Request.Cookies["Usuario"]["sesion"], Session["Sesion"].ToString()) || Session["Nivel"].ToString() == "3")
        {
            Response.Redirect("index.aspx");
        }
        Session["Titulo"] = "REPORTE EN GENERAL";
        Session["Error"] = "";
        if (Session["Cliente"].ToString() != "")
        {
            Cliente = " AND Casos.Cliente = '" + Session["Cliente"].ToString() + "'";
        }
        else
        {
            Cliente = "";
        }

    }
    protected void dlPeriodo_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (dlPeriodo.SelectedIndex != 6)
        {
            lblDesde.Visible = false;
            lblHasta.Visible = false;
            tbDesde.Visible = false;
            tbHasta.Visible = false;
        }
        else
        {
            lblDesde.Visible = true;
            lblHasta.Visible = true;
            tbDesde.Visible = true;
            tbHasta.Visible = true;
        }
    }
    protected void btnVer2_Click(object sender, ImageClickEventArgs e)
    {
        
        if (dlPeriodo.SelectedIndex != 6)
        {
            SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
            Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;
            
        }
        else
        {
            DateTime Fecha;
            if (DateTime.TryParse(tbDesde.Text, out Fecha))
            {
                if (DateTime.TryParse(tbHasta.Text, out Fecha))
                {
                    SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
                    Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;

                }
                else
                {
                    string Formato = "";
                    if (funciones.Fecha() == "101")
                    {
                        Formato = " mm/dd/aaaa";
                    }
                    else
                    {
                        Formato = " dd/mm/aaaa";
                    }
                    Session["Error"] = "La fecha debe ser de la forma" + Formato;
                }
            }
            else
            {
                string Formato = "";
                if (funciones.Fecha() == "101")
                {
                    Formato = " mm/dd/aaaa";
                }
                else
                {
                    Formato = " dd/mm/aaaa";
                }
                Session["Error"] = "La fecha debe ser de la forma" + Formato;
            }

        }
            
    }
protected void grdCartelera2_PageIndexChanged(object sender, EventArgs e)
    {
        SqlDataSourceBusqueda2.SelectCommand = Session["Sql"].ToString();
    }
protected void grdCartelera2_Sorted(object sender, EventArgs e)
    {
        SqlDataSourceBusqueda2.SelectCommand = Session["sql"].ToString();  
    }
private void ExportGridToExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Redex_ReporteCasos"));
        Response.Charset = "";
        StringWriter stringwriter = new StringWriter();
        HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
        GridView2.RenderControl(htmlwriter);
        Response.Write(stringwriter.ToString());
        Response.End();
        ExportGridToExcel();

    }      
    protected void btnexportExcel_Click(object sender, ImageClickEventArgs e)
     {
        ExportGridToExcel(); 
     }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (funciones.Anexos(((System.Web.UI.WebControls.HyperLink)(e.Row.Cells[1].Controls[0])).Text))
            {
                Image Imagen = new Image();
                Imagen.ImageUrl = "~/Imagenes/Iconos/anexo.png";
                e.Row.Cells[0].Text = "Si";
                
            }
            else
            {
                e.Row.Cells[0].Text = "No";
                
            }
            
            string BajoContrato = e.Row.Cells[15].Text.ToString();
            if (BajoContrato == "False")
            {
                e.Row.Cells[15].Text = "No";
            }
            else
            {
                e.Row.Cells[15].Text = "Si";
            }
            btnexportExcel_Click(null, null);
        }
        
    }
    public override void VerifyRenderingInServerForm(Control control) {} 
}

ASPX

<table style="width: 770px; height: 492px">
            <tr>
                <td align="center" style="height: 7%;" valign="middle">
                    <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="En el periodo" Font-Size="Small"></asp:Label></td>
                <td align="center" style="height: 7%;" valign="middle">
                    <asp:DropDownList ID="dlPeriodo" runat="server" BackColor="AliceBlue"
                        EnableTheming="True" Font-Bold="True" Font-Names="Century Gothic" ForeColor="#00C000"
                        OnSelectedIndexChanged="dlPeriodo_SelectedIndexChanged" Width="192px" Font-Size="Small" AutoPostBack="True">
                        <asp:ListItem Value="0">Hoy</asp:ListItem>
                        <asp:ListItem Value="1">1 Dia</asp:ListItem>
                        <asp:ListItem Value="5">5 Dias</asp:ListItem>
                        <asp:ListItem Value="7">7 Dias</asp:ListItem>
                        <asp:ListItem Value="15">15 Dias</asp:ListItem>
                        <asp:ListItem Value="30">30 Dias</asp:ListItem>
                        <asp:ListItem Value="6">Especifico</asp:ListItem>
                    </asp:DropDownList></td>
                <td align="center" style="height: 7%; text-align: right;" valign="middle">
                    <asp:ImageButton ID="btnVer" runat="server" Height="24px" ImageUrl="~/Imagenes/Iconos/buscar.png"
                        OnClick="btnVer_Click" Width="22px" /></td>
                <td align="left" colspan="1" valign="middle" class="style1">
                    &nbsp;<asp:ImageButton ID="btnVer0" runat="server" 
                        Height="20px" ImageUrl="~/Imagenes/Iconos/excel.png"
                        OnClick="btnVer2_Click" Width="26px" /> 
                    <asp:ImageButton ID="btnExcel" style="visibility: hidden; display: none;" runat="server" ImageUrl="~/Imagenes/Iconos/excel.png"
                        OnClick="btnexportExcel_Click" Width="20px" Height="21px"/>
                    </td>
                <td align="center" colspan="2" style="height: 7%" valign="middle">
                    &nbsp;</td>
            </tr>
            <tr>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:Label ID="lblDesde" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="Desde" Visible="False" Font-Size="Small"></asp:Label></td>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:TextBox ID="tbDesde" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px" 
                        Font-Size="Small"></asp:TextBox></td>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:Label ID="lblHasta" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="Hasta" Visible="False" Font-Size="Small"></asp:Label></td>
                <td align="left" valign="middle" class="style2">
                    <asp:TextBox ID="tbHasta" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px" 
                        Font-Size="Small"></asp:TextBox></td>
                <td align="center" style="height: 8%" valign="middle" colspan="2">
                    &nbsp;</td>
            </tr>
            <tr>
                <td align="left" colspan="6" style="height: 105%" valign="top">
                <%if(Session["Nivel"].ToString() != "4"){ %>
                    <asp:GridView ID="GridView2" runat="server" AllowPaging="False"
                        CellPadding="2" DataSourceID="SqlDataSourceBusqueda2" Font-Names="Century Gothic"
                        ForeColor="#333333" GridLines="None" PageSize="50" Width="769px" 
                        AutoGenerateColumns="False" Font-Size="Small" 
                        OnPageIndexChanged="grdCartelera2_PageIndexChanged" 
                        OnSorted="grdCartelera2_Sorted"  OnRowDataBound="GridView2_RowDataBound">
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <Columns>
                            <asp:ImageField HeaderText="Anexos">
                            </asp:ImageField>
                            <asp:HyperLinkField DataNavigateUrlFields="N&#176; Caso" DataNavigateUrlFormatString="Casos.aspx?idCaso={0}"
                                DataTextField="N&#176; Caso" HeaderText="Caso"
                                SortExpression="N&#176; Caso" />
                            <asp:BoundField DataField="Cliente" HeaderText="Cliente" SortExpression="Cliente" />
                            <asp:BoundField DataField="ContactoCliente" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Contacto Cliente" SortExpression="ContactoCliente" />
                            <asp:BoundField DataField="TipoCaso" HeaderText="Tipo Caso" SortExpression="TipoCaso" />
                            <asp:BoundField DataField="Asunto" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Asunto" SortExpression="Asunto" />
                            <asp:BoundField DataField="Asignado" HeaderText="Tecnico" SortExpression="Asignado" />
                            <asp:BoundField DataField="Causa_Raiz" HeaderText="Causa Raiz" SortExpression="Causa_Raiz" />
                            <asp:BoundField DataField="Zona" HeaderText="Zona" SortExpression="Zona" />
                            <asp:BoundField DataField="Sector" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Sector" SortExpression="Sector" />
                            <asp:BoundField DataField="Estado Actual" HeaderText="Estado" SortExpression="Estado Actual" />
                            <asp:BoundField DataField="Prioridad" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Prioridad" SortExpression="Prioridad" />
                            <asp:BoundField DataField="HorasTrabajadas" HeaderText="Horas Trabajadas" SortExpression="HorasTrabajadas" />
                            <asp:BoundField DataField="Evaluacion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Evaluacion" SortExpression="Evaluacion" />
                            <asp:BoundField DataField="EquiposAtendidos" HeaderText="Equipos Atendidos" SortExpression="EquiposAtendidos" />
                            <asp:BoundField DataField="BajoContrato" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Bajo Contrato" SortExpression="BajoContrato" />
                            <asp:BoundField DataField="N° Factura" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="N°Factura" SortExpression="N° Factura" />
                            <asp:BoundField DataField="Diagnostico" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Diagnostico" SortExpression="Diagnostico" />
                            <asp:BoundField DataField="Solucion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Solucion" SortExpression="Solucion" />
                            <asp:BoundField DataField="Reportado" HeaderText="Reportado" SortExpression="Reportado" />
                            <asp:BoundField DataField="Cerrado" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Cerrado" SortExpression="Cerrado" />
                            <asp:BoundField DataField="Vencimiento" HeaderText="Vencimiento" SortExpression="Vencimiento" />
                        </Columns>
                        <RowStyle BackColor="#EFF3FB" />
                        <EditRowStyle BackColor="#2461BF" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                    <%}%>
<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" ConnectionString="<%$ ConnectionStrings:conexion %>"
                        ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"></asp:SqlDataSource>

有多种解决方案,但您需要尝试多种解决方案,以便分析哪一种适合您的需求。

解决方案 1 如果您打算执行服务器端事件,您可以简单地从您的代码后面调用该方法,而不是伪造点击。在后面的代码中像这样调用您的事件方法。

btnExcel_Clicked(null, null);

您可以这样食用:

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    btnExcel_Clicked(null, null); //  I assume your btnExcel button is linked to this event.
}

解决方案 2 如果要求您只能使用 JavaScript/Jquery 这可能会有所帮助。

var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger", 
    "$("#"+ myButtonID +"").trigger("click");", true);

解决方案 3 解决方案 2,带有 javascript 事件。

var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger",
    "document.getElementById(" + myButtonID + ").onclick();", true);

我认为在 RowDataBound 事件上调用它不是一个好主意,因为它不仅会在加载网格视图时多次触发它。因此,您必须在调用 GridView2.DataBind() 方法之后调用它,而不是在 RowDataBound 事件中调用它。


解决方案 4 这是一个纯粹的、基于页面流的解决方案。诀窍是通过使用 CodeBehind 标志从 javascript 执行 javascript。以下是您将如何做到这一点:

首先在CodeBehind中声明一个属性。

public bool ShouldTriggerClickEvent { get; set; }

然后,在您的 Page_Load 活动中,将 flase 作为值分配给此 属性,并在您的 RowDataBound 活动完成后将其设为 true触发。参见:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostback)
    {
        ShouldTriggerClickEvent = false;
    }
}

现在,在您的 RowDataBound 事件中将其设置为真。

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    ShouldTriggerClickEvent = true;
}

现在,当页面加载完成时,您需要在客户端检查此标志,如果标志为真,则执行代码。如下所示:

<script>
    $(document).ready(function(){
        function shouldTriggerClickEvent(){
            return '<%= ShouldTriggerClickEvent %>' == 'True';
        }
        if (shouldTriggerClickEvent()){
            $("#<%=btnExcel.ClientID%>").trigger("click");
        }
    });
</script>

我已经提到了到目前为止我可以记住的多个解决方案,您可以看到哪个适合您。


更新

当您询问在哪里调用该方法时,我建议您在绑定 DataSource.

后立即调用该方法
// After this line
GridView2.DataBind(); //  so each time the data is populated in it, this will method will be called
btnExcel_Clicked(null, null);

您还可以检查您的 DataSource 中是否有项目,只有这样您才可能想要调用它,正如您在加载 GridView 时询问的那样,我认为这意味着,只有在它有之后才加载其中的行。

// Lets assume you have a DataTable object that is the DataSource of the GridView
var dataTable = GetDataTable(); // Some method that will fetch the rows

GridView2.DataSource = dataTable;
GridView2.DataBind(); //  so each time the data is populated in it, this will method will be called
if (dataTable != null && dataTable.Rows.Count > 0)
{
    btnExcel_Clicked(null, null);
}

更新 2

好的,所以你想在数据绑定到你的 GridView 之后调用执行事件,并且你正在使用 SqlDataSource 绑定 GridView。这是我的修改建议。

替换您的 SqlDataSource 以包含 OnSelected 事件。

<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" 
     ConnectionString="<%$ ConnectionStrings:conexion %>"
     ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"
     OnSelected="SqlDataSourceBusqueda2_Selected">
</asp:SqlDataSource>

并在 CodeBehind

中添加 method/event
protected void SqlDataSourceBusqueda2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    // Your Code goes here.
    btnExcel_Clicked(null, null);
}