簡體   English   中英

在updatepanel中輸入文件並回發觸發器asp

[英]Input file inside updatepanel and postback trigger asp

我在UpdatePanel中使用輸入文件,並且效果很好。 但是使用UpdatePanel PostBackTrigger時,ScriptManager.RegisterStartupScript不起作用。

如果我不使用PostBackTrigger,則ScriptManager.RegisterStartupScript可以工作,但輸入文件不能。

我在C#中使用ASP Web窗體

這是源代碼。

.aspx:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="up_upload" runat="server" UpdateMode="Conditional">
        <Triggers>
            <asp:PostBackTrigger ControlID="btn_upload" />
        </Triggers>
        <ContentTemplate>
            <input type="file" id="file_test" runat="server" />
            <asp:Button ID="btn_upload" runat="server" Text="Subir" CausesValidation="False" OnClick="btn_upload_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

.cs

protected void btn_upload_Click(object sender, EventArgs e)
{
    try
    {
        string message = "file not uploaded!";
        if (file_test.PostedFile != null)
        {
            string fn = file_test.PostedFile.FileName;
            string only_path = Server.MapPath(".");

            file_test.PostedFile.SaveAs(only_path + "//Images//" + fn);

            ScriptManager.RegisterStartupScript(up_upload, up_upload.GetType(), Guid.NewGuid().ToString(), "alert('server path: ' + '" + only_path.Replace("\\", "\\\\") + "');", true);
            message = "file uploaded!";

        }

        ScriptManager.RegisterStartupScript(up_upload, up_upload.GetType(), Guid.NewGuid().ToString(), "alert('" + message + "');", true);

        up_upload.Update();
    }
    catch (Exception ex)
    {
        ScriptManager.RegisterStartupScript(up_upload, up_upload.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message + "');", true);
    }
}

解決了! 當我發回整頁帖子時,我使用ClientScript.RegisterStartupScript而不是ScriptManager.RegisterstartupScript。

ClientScript.RegisterStartupScript(up_upload.GetType(), 
Guid.NewGuid().ToString(), "<script>alert('" + message + "');</script>");

感謝您的幫助!

使用asp.net文件上傳器控件的FileUpload始終需要整頁回發請求。

這是所有AJAX框架中用於對應用程序進行異步調用的XmlHttpRequest組件的限制。 我建議您兩個解決方案:

  1. 回傳整頁帖子 (**即不使用updatepanel中的文件上傳)
  2. 如果你希望一個完整的回傳,嘗試其他的解決方案,如懸浮窗文件上傳插件上傳文件。 當我想要一個很酷的文件上傳界面時,我總是使用它。 這是非常容易使用 。 請參考其文檔以了解其用法,或嘗試鏈接進行學習。

相信我,這很容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM