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

时间:2018-01-18 18:22:45

标签: javascript c# jquery asp.net gridview

我试图在" Fileupload"上传一个文件onchange事件。在gridview中控制。 意味着当用户上传文件时,我自己需要将文件内容保存在DB中。 所以,我在fileupload控件的更改上手动调用了按钮控件的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;
}

3 个答案:

答案 0 :(得分:0)

最简单的方法是从代码中分配onchange事件,这样您就可以轻松获得正确的按钮。因此,为GridView创建一个RowDataBound事件。

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

然后在RowDataBound方法中,使用FindControl来定位和转换FileUpload和Button。在该方法中,您可以指定change事件以触发相应按钮的PostBack。

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 + "','')");
    }
}

答案 1 :(得分:0)

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

由于您说您正在使用gridview,因此可能有多行,每行都有自己的fileupload和按钮控件。您需要在网格视图中获取与此行关联的按钮控件。要获取相关按钮,您应该使用如下所示的jquery代码,因为相关按钮紧跟在fileupload控件之后。

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

答案 2 :(得分:0)

您的实施只会改变:

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();
}

我测试过它完全没问题!

相关问题