Using UploadPersistedFile and making file upload mandatory

Last post 10-18-2011, 10:30 AM by MarjaR. 3 replies.
Sort Posts: Previous Next
  •  10-18-2011, 7:20 AM 70438

    Using UploadPersistedFile and making file upload mandatory

    I'm using UploadPersistedFile in an ASP.NET 4.0 form to ask the user to upload a photo, and I would like to make that upload mandatory.
    I can't simply use a RequiredFieldValidator because that won't accept the UploadPersistedFile instance as its ControlToValidate.
     
    So how can I enforce the file upload?
     
    Best regards, Marja 

    Regards, Marja
  •  10-18-2011, 8:35 AM 70446 in reply to 70438

    Re: Using UploadPersistedFile and making file upload mandatory

    Hi MarjaR,
     
    Please try the example below
     
    <%@ Page Language="C#" %>

    <%@ Register Namespace="CuteWebUI" Assembly="CuteWebUI.AjaxUploader" TagPrefix="CuteWebUI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        protected void uploader1_UploadCompleted(object sender, UploaderEventArgs[] args)
        {
            hf1.Value = args.Length.ToString();
        }
    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <CuteWebUI:UploadPersistedFile ID="uploader1" runat="server" OnUploadCompleted="uploader1_UploadCompleted">
            </CuteWebUI:UploadPersistedFile>
            <asp:HiddenField ID="hf1" runat="server" />
            <asp:Button ID="btnSubmit" runat="server" OnClientClick="return verify()" Text="submit" />
        </form>
    </body>
    </html>

    <script type="text/javascript">

    function verify()
    {
        var hf1=document.getElementById("<%=hf1.ClientID %>");
        if(hf1.value=="")
        {
            alert("please upload a file before submit");
            return false;
        }
        return true;
       
    }
    </script>
     
    Regards,
     
    Ken
  •  10-18-2011, 9:37 AM 70455 in reply to 70446

    Re: Using UploadPersistedFile and making file upload mandatory

    Thanks Ken, I will try that. 
     
    But that solution is client-side only and I would prefer to implement some kind of server-side validation (as well). Is that possible?
     
     

    Regards, Marja
  •  10-18-2011, 10:30 AM 70457 in reply to 70455

    Re: Using UploadPersistedFile and making file upload mandatory

    I'm sorry... of course that validation trick can be done server-side as well.
     
    It's working just fine now with an (hidden) extra TextBox that gets its value in the server-side OnFileUploaded event, and a RequiredFieldValidator on that TextBox.
     
    Thank you for your help! 

    Regards, Marja
View as RSS news feed in XML