【问题标题】:Programmatically call OnClick method on ASP LinkButton in C#在 C# 中以编程方式调用 ASP LinkBut​​ton 上的 OnClick 方法
【发布时间】:2021-06-17 13:45:21
【问题描述】:

我有这个带有 LinkBut​​ton 的 ASP 网络表单

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LLPIposAttachment.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>iPOS Attachment</title>
    <style type="text/css">
        body{
            font-family: Arial;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>iPOS Attachments List</h2>
        </div>
        <asp:GridView ID="AttachmentList" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="ATTACH_NAME" HeaderText="File Name" />
                <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("ATTACH_ID") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <!-- log part -->
        <asp:Label ID="lbLog" runat="server"></asp:Label>
        <!-- log part -->
    </form>
</body>
</html>

在某些特定情况下,我需要以编程方式调用 OnClick 方法。 GridView 是从数据库中填充的,当只读取一行时,我需要自动调用 OnClick 方法。 如何在 C# 中做到这一点?或者它必须以某种方式在 Javascript 或其他东西中完成?

【问题讨论】:

  • 当只从数据库中读取一行时,页面甚至还没有渲染。为什么不分享逻辑并从那里调用它?也就是说,如果只有一个文件要下载,那么就提供它,否则,提供gridview?

标签: c# webforms


【解决方案1】:

解决方案 1:

只需调用事件委托:DownloadFile(lnkDownload, EventArgs.Empty);

解决方案 2:模拟点击(不是很“干净”的解决方案)

此代码适用于asp:Button

使用这个js函数:

function eventFire(el, etype) {
    if (el.fireEvent) {
        el.fireEvent('on' + etype);
    } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
    }
}

onload js 脚本中,运行这个:

var b = document.getElementById(id_button);
eventFire(b, 'click');

其中id_buttonlnkDownload.ClientID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多