簡體   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