title: Prevent MVC form submit using Javascript Function
body: <p>I have a <code>upload.ascx</code> in my project. It will be loaded inside Jquery Popup. </p>
  
  <p>The <code>upload.ascx</code> contains <code>File Upload</code> control. The File upload control will uploads <code>.xlsx and .xls</code> files. I have added <code>Java script</code> function to do this validation (To prevent unnecessary files uploaded).</p>
  
  <p><code>Onchange of FileUpload</code> control and <code>Onclick of Submit button</code> the same Validation function will be called. </p>
  
  <p>The File Upload Validation Function is working for both calling. If the user clicks submit button the same function is getting called and working fine. </p>
  
  <p><strong>My Problem is:</strong> In My validation function i have written <code>return false</code>. After displaying the alert Message, the Page is getting redirected to some URL (<code>localhost/Admin/Authorization/AcceptFile.aspx</code>). <code>AcceptFile</code> is my ActionResult name. It should not happen. The Function is returning False. But the Form is getting redirected to Above URL why.?</p>
  
  <p>I have kept debugger in my Action Result that is not getting called if its wrong File(Its correct). If its correct File the Index file will be loaded with Success message(Action result is getting called and working Fine). .</p>
  
  <p>I suspect MVC Form. If wrong file is uploaded the redirection is happening with out calling Action Result this should be stopped.</p>
  
  <pre><code>&lt;% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
         {%&gt;
  </code></pre>
  
  <p><strong>My Javascript Function:</strong></p>
  
  <pre><code>function checkfile(sender) {
          var validExts = new Array(".xlsx", ".xls");
          var fileExt = sender.value;
          var strValue = false;
          fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
          if (validExts.indexOf(fileExt) &lt; 0) {
              ShowMessage(-1, "Invalid file selected, valid files are .xlsx and .xls types.");
              strValue = false;
          }
          else {
              strValue = true;
          }
          return strValue;
      }
  </code></pre>
  
  <p><strong>My upload.ascx Code:</strong></p>
  
  <pre><code>&lt;div&gt;
      &lt;% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
         {%&gt;
  
            &lt;input type="file" id="fileAuthorization" name="fileAuthorization" onchange="checkfile(this);" /&gt;
  
            &lt;input type="submit" id="btnSave" name="btnSave" value="Upload" onclick="javascript:return checkfile(document.getElementById('fileAuthorization'))" /&gt;
  
      &lt;%} %&gt;
  &lt;/div&gt;
  </code></pre>