简体   繁体   中英

Pass label value from C# to bootstrap modal

I am using a bootstrap modal popup with Ajax sync File Upload inside the modal. When the user browses for a file, the C# code gets fired.

The only problem is that there is a label inside the modal that is supposed to tell the user if the upload went fine or not and why (from the c# code) and the value of the label is always null!

  1. Why is that?
  2. How can I resolve this?

Thanks!

bootstrap modal code:

<div class="modal-content">
<div class="modal-header">
    <h4 class="modal-title" id="myModalLabel1">Upload Your Photo</h4>
</div>
<Myajax:ToolkitScriptManager ID="scriptManager1" runat="server" />

<div class="btn btn-file">
    <Myajax:AsyncFileUpload ID="FileUpload1" 
        CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
        ThrobberID="imgLoad" OnUploadedComplete="UploadFile"/><br />
    <asp:Label ID="lblUpload" runat="server" class="text-success pull-left" Text="" ></asp:Label>
</div>

<div class="modal-footer">
    <asp:Image ID="imgLoad" CssClass="pull-left" style="width: 35px; height: 35px" runat="server" ImageUrl="Images/loading2.gif" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button id="btnSubmit" runat="server" type="button" class="btn btn-default" onserverclick="UploadFile">Upload</button>
</div>

c# code:

protected void UploadFile(object sender, EventArgs e)
{
    string fileName = Server.HtmlEncode(FileUpload1.PostedFile.FileName);
    string extension = System.IO.Path.GetExtension(fileName);

    if (extension == ".jpeg")
    {
        string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
        string SaveLocation = Server.MapPath("Data") + "\\" + fn;
        try
        {
            FileUpload1.PostedFile.SaveAs(SaveLocation);
            Response.Write("The file has been uploaded.");
        }
        catch (Exception ex)
        {
            lblUpload.Text = "Somthing";
        }
    }
    else
    {
        lblUpload.Text = "Only jpeg is allow";
    }
}

Actually, looking at it, you have a label, and you can set it when you step in, but you have no way for the interface to update to reflect the changes. What you need to do is wrap the label in an UpdatePanel so the label can update the view once the text value is set.

UPDATE Sorry about the above info. Let me go into more detail, because the AsyncFileUpload is a weird beast. I went back and looked at what I did because I am using it with jCrop to create an image cropper before upload.

The AsyncFileUpload (from here out AFU) allows you to specify scripts to be executed on the client with events. I can only assume this is because the AFU actually uses an iFrame behind the scenes to do an asyncronous post with the image data. If you search around you will find this approach used by people for the same goal prior to the AFU. Using the client event triggers, you can call a function in JavaScript that executes OnClientUploadStarted, OnClientUploadComplete, and OnClientUploadError; you specify the JavaScript function as the value.

For what you are trying to do, the OnClientUploadComplete would be the best method to use. Now, because the AFU uses an iFrame, any value set to controls during it's PostBack sequence is actually in a different frame than your page. This means simply updating the label or even updating the UpdatePanel will not work because it's not your current frame in the page. Instead, you need to tell your current frame what to do, and in this case of just updating a label, we can store the value in the session. Sessions are maintained per client browser so an iFrame from the AFU will use the same session as the current view.

In the AFU UploadFile method, handling the UploadedComplete event, we set a session variable to the text you want in the label. Then, we need to trigger the UpdatePanel to refresh. An easy way to do this is hide a button in the UpdatePanel and make it the trigger using an AsyncPostBackTrigger. In the OnClick event for the button, set the label to the value of the session key you set from the AFU event.

The final thing is the trigger the button click. Using the OnClientUploadComplete we call a JavaScript function that will trigger a PostBack event for the button, thus triggering the button Click event, and ultimately triggering the UpdatePanel update.

Here is some code on it working with your example: HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function _panelRefresh() {
            __doPostBack('<%= panelUpdate.ClientID%>', '');  // client id of button control
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="scriptMan1" EnablePartialRendering="true"></asp:ScriptManager>
        <div>
            <asp:AsyncFileUpload ID="FileUpload1"
                CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Traditional" UploadingBackColor="#CCFFFF"
                ThrobberID="imgLoad" OnUploadedComplete="UploadFile" OnClientUploadComplete="_panelRefresh" />
            <asp:UpdatePanel runat="server" ID="updatePanel1" ChildrenAsTriggers="true">
                <ContentTemplate>
                    <asp:Button runat="server" ID="panelUpdate" OnClick="panelUpdate_Click" style="display:none;" />                    
                    <asp:Label ID="lblUpload" runat="server" class="text-success pull-left" Text=""></asp:Label>
                </ContentTemplate>
                <Triggers><asp:AsyncPostBackTrigger ControlID="panelUpdate" EventName="Click" /></Triggers>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

Code Behind:

protected void UploadFile(object sender, EventArgs e) {
    string fileName = Server.HtmlEncode(FileUpload1.PostedFile.FileName);
    string extension = System.IO.Path.GetExtension(fileName);

    if (extension == ".jpeg") {
        string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
        string SaveLocation = Server.MapPath("Data") + "\\" + fn;
        try {
            FileUpload1.PostedFile.SaveAs(SaveLocation);
            Response.Write("The file has been uploaded.");
        } catch (Exception ex) {
            Session["uploadLabel"] = "Something";// use session to store label text
        }
    } else {
        Session["uploadLabel"] = "Only jpeg is allow";  // use session to store label text
    }
}
protected void panelUpdate_Click(object sender, EventArgs e) {
    lblUpload.Text = Session["uploadLabel"].ToString() ?? "";   // session value or empty if session is null
}

Incidentally, you can shorten some of your FileName and Save references with the AFU control. Commented the lines with //SHORTENED to show it:

protected void UploadFile(object sender, EventArgs e) {
    string extension = System.IO.Path.GetExtension(FileUpload1.FileName);// SHORTENED

    if (extension == ".jpeg") {
        string fn = FileUpload1.FileName;   // SHORTENED
        string SaveLocation = Server.MapPath("Data") + "\\" + fn;
        try {
            FileUpload1.SaveAs(SaveLocation);   // SHORTENED
            Response.Write("The file has been uploaded.");
        } catch (Exception ex) {
            Session["uploadLabel"] = "Something";// use session to store label text
        }
    } else {
        Session["uploadLabel"] = "Only jpeg is allow";  // use session to store label text
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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