繁体   English   中英

调用按钮在gridview内单击文件上传

[英]Calling button click on file upload inside gridview

我正在尝试在gridview中上传“ Fileupload”控件的文件onchange事件。 意味着当用户上传文件时,我本身需要将文件内容保存在DB中。 因此,我曾在文件上传控件的更改上手动调用了按钮控件的click事件,但它的抛出就像“无效的回发或回调参数...”之类的异常一样。

我的GridView代码:

<asp:GridView runat="server" ID="grd" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="StudentID" HeaderText="Student ID" />
        <asp:BoundField DataField="StudentName" HeaderText="Name" />
        <asp:TemplateField HeaderText="Upload">
            <ItemTemplate>
                <asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" onChange="FileUploadCall(this)" />
                <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我的脚本代码:

<script type="text/javascript">
    function FileUploadCall(fileUpload) {
        if (fileUpload.value != '') {
            var a = $('#<%=grd.ClientID %>').find('[id*="btnUpload"]');
            a.click();
        }
    }
</script>

CS文件中的“我的隐藏按钮”手动单击创建:

protected void Upload(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gvr = (GridViewRow)btn.Parent.Parent;

    FileUpload lbleno = (FileUpload)gvr.FindControl("FileUpload1");

    lbleno.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(lbleno.FileName)));
    //lblMessage.Visible = true;
}

最简单的方法是从后面的代码分配onchange事件,以便您可以轻松获得正确的按钮。 因此,为GridView创建RowDataBound事件。

<asp:GridView ID="grd" runat="server" OnRowDataBound="grd_RowDataBound">

然后在RowDataBound方法中,使用FindControl定位并投射FileUpload和Button。 在方法中,您可以分配更改事件以触发相应按钮的回发。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //use findcontrol to locate the controls in the row and cast them
        Button btn = e.Row.FindControl("btnUpload") as Button;
        FileUpload fu = e.Row.FindControl("FileUpload1") as FileUpload;

        //assign the button postback to the change of the fileupload
        fu.Attributes.Add("onchange", "__doPostBack('" + btn.UniqueID + "','')");
    }
}

您的jquery代码获取了要上传的按钮,可能是原因。

既然您说的是使用gridview,所以可能会有多行,每行都有自己的文件上传和按钮控件。 您需要在网格视图中获取与此行关联的按钮控件。 要获取关联的按钮,您应该使用如下所示的jquery代码,因为关联的按钮紧随fileupload控件之后。

if (fileUpload.value != '') {
    var a = $(fileUpload).next("[id*='Button1']");
    a.click();
  }

您的实现很好,只有更改:

a.click(); => a[0].click();  //important!!

我希望回发中不会发生绑定:

if (!IsPostBack)
{
    var list = new List<Student>();
    list.Add(new Student() {StudentID = 1, StudentName = "111"});
    list.Add(new Student() {StudentID = 2, StudentName = "222"});
    grd.DataSource = list;
    grd.DataBind();
}

我已经测试了它的工作原理!

暂无
暂无

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

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