Link to home
Start Free TrialLog in
Avatar of WorknHardr
WorknHardr

asked on

Html.BeginForm Submit File Upload Empty alert?

This work fine for ASP:Button, but I'm working with MVC.

- How do I code alert box if file upload is empty

- asp:button -
<asp:FileUpload ID="fileImageUrl" ClientIDMode="Static" runat="server" size="40" />

<asp:Button ID="btnUpload" 
         ClientIDMode="Static" 
         Text="Upload Picture" 
         runat="server" 
         OnClientClick="return validateUpload();" 
         onclick="btnUpload_Click" />

<script type="text/javascript">
        function validateUpload() {
            if (document.getElementById("fileImageUrl").value == "") {
                alert("Please select an image to upload.");
                return false;
            }
            return true;
        }
    </script>

Open in new window


- MVC -
@using (Html.BeginForm("Upload", "FileManager", null, FormMethod.Post, 
               new { enctype = "multipart/form-data", @class = "myform" }))
        {
            <label>File Upload</label>
            <input type="file" name="filename" style="padding: 2px 5px"/>  
            <br />   
            <br />       
            <input type="submit" value="Upload File" style="padding: 2px 5px" />

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of WorknHardr
WorknHardr

ASKER

I wasn't sure if 'OnClick' would work like that, I'll let you know...
onclick is standard Javascript. OnClientClick is just special notation for ASP.NET Web Forms. It is output as an onclick on the rendered tag.
Okay
Here is working code:

@using (Html.BeginForm("Upload", "FileManager", null, FormMethod.Post, 
               new { enctype = "multipart/form-data", @class = "myform" }))
        {
            <label>File Upload</label>
            <input type="file" id="filename" name="filename" style="padding: 2px 5px"/>  
            <br />   
            <br />       
            <input type="submit" value="Upload File" style="padding: 2px 5px" 
              onclick="return validateUpload();" />
}

 <script type="text/javascript">
            function validateUpload()
            {
                if (!$("filename").val())                     
                {
                    alert("Please select an image to upload.");
                    return false;
                }
                return true;
            }
        </script>
        }
    </script>

Open in new window

danka
Help, spoke to soon. The Alert opens no matter if Input is empty or not!