Disable form submission in MVC using a JavaScript function

In my project, there is an upload.ascx file that will be loaded inside a Jquery Popup.

The upload.ascx file contains a File Upload control that uploads .xlsx and .xls files. To validate the file uploads and prevent unnecessary files from being uploaded, I have added a JavaScript function.

Whenever there is a change in the FileUpload control or when the Submit button is clicked, the validation function is called.

The File Upload Validation Function works correctly for both scenarios. However, my issue arises when the validation function returns false. After displaying an alert message, the page redirects to a specific URL (

localhost/Admin/Authorization/AcceptFile.aspx
) even though the function should prevent this from happening.

Upon further investigation, I noticed that if the wrong file is uploaded, the redirection occurs without calling the Action Result, which should be prevented.

<% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
       {%>

JavaScript Function:

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) < 0) {
            ShowMessage(-1, "Invalid file selected, valid files are .xlsx and .xls types.");
            strValue = false;
        }
        else {
            strValue = true;
        }
        return strValue;
    }

upload.ascx Code:

<div>
    <% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
       {%>

          <input type="file" id="fileAuthorization" name="fileAuthorization" onchange="checkfile(this);" />

          <input type="submit" id="btnSave" name="btnSave" value="Upload" onclick="javascript:return checkfile(document.getElementById('fileAuthorization'))" />

    <%} %>
</div>

Answer №1

After investigating, I was able to identify the issue.

It appears that my initial suspicion was correct. The problem lies with:

onsubmit = "javascript:return checkfile(document.getElementById('fileAuthorization'))"

The correct way to handle this is to include it within the Form tag itself:

<% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "javascript:return checkfile(document.getElementById('fileAuthorization'))" }))
       {%>

Prior to this correction, the function was triggered by the Submit button Onclick event:

<input type="submit" id="btnSave" name="btnSave" value="Upload" onclick="javascript:return checkfile(document.getElementById('fileAuthorization'))" />

Upon making the necessary adjustments, everything now functions correctly (Validations and File Upload for both the Submit button Onclick event and the File Upload control onchange event).

However, I am still puzzled as to why the return false statement did not work for the Submit button click, but does work for the Fileupload onchange events.

Furthermore, I noticed a redirection issue occurring previously. This was resolved by switching to an MVC Form configuration (the redirection no longer takes place). The reason behind this change in behavior remains unclear.

Answer №2

Make a simple change to your submission process:

<button type="button" id="btnSave" name="btnSave" onclick="validateFile(document.getElementById('fileAuth'))" ></button>

This adjustment will prevent the form from submitting automatically.

When you are prepared to submit the form, you can use JavaScript in your callback function:

document.getElementById('form-id').submit();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing mouse hover functionality for fieldset in EXTJS

I am looking to enhance the following code snippet by adding a mouse hover event that changes the background color of the fieldset item and displays an image next to it. Can someone assist me with this modification? var mainGroup = { ...

Sharing JSON data between PHP and JavaScript/AJAX

In order to validate strings on my website, I am developing a validation mechanism using both Javascript and ajax for client-side validation and PHP for server-side validation. It is essential for both PHP and Javascript to utilize the same variables, suc ...

The firebaseui.js code encountered an error because it was unable to read the property 'call' as it was undefined

Currently, I am facing an issue while trying to implement Firebase ui auth in my app by referring to Google's Github documentation. While the email sign-in functionality is working smoothly, I am encountering problems with the phone sign-in option. ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...

Utilize specific CSS attributes from a class and apply them to a DOM element

It's clear that the question at hand is more complex than it initially appears. I'm not just looking for a way to apply a CSS class to a DOM element, as I'm already familiar with that (<div class="MyCssCLass"></div>) My goal is ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

Assign the path parameter to the component key in the Route

One of the routes in my application is defined as shown below: <Route exact path="/licenses/:type?" component={Licenses} /> I want the component to re-render every time the type parameter changes. According to react-router documentation, I ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

Dynamically change the content of the DataTable by utilizing jQuery

I am facing an issue with updating a DataTable using jQuery when the contents of the table are modified. Initially, I have a HTML table with an empty tbody, which is populated dynamically based on selected filters such as select options. The table uses Dat ...

Issue with Accessing Subdomain Cookies on Express Backend Using CORS and Cookie-Parser

I am currently tackling a challenge in my MERN (MongoDB, Express, React, Node.js) application related to receiving cookies from subdomains in my Express backend. Despite implementing CORS and cookie handling successfully for a simple localhost origin, I am ...

Obtaining the route name in Vue.js within the App.vue component

After utilizing vue-cli with webpack to construct the vue project, I incorporated vue-meta-info for SEO purposes. I am facing an issue in setting up the page title using templates and route names. Unfortunately, I am unable to access the variable in the r ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Error message: React is unable to locate the map container in the Leaflet library during rendering

I am working with a custom React and Leaflet.js component... export const CustomMapSetLocationComponent = (props) => { React.useEffect(() => { let marker = null let map = null var container = L.DomUtil.get('setLocationMap') ...

Unable to administer AuthenticationController

I am attempting to inject a controller into my app.run function, but I keep encountering the following error: Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=AuthenticationControllerProvider%20%3C-%20AuthenticationCon ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

The JavaScript code appears to be missing or failing to execute on the website

Encountering a console error while trying to integrate jQuery into my website. The JavaScript file is throwing an error in the console that says: Uncaught ReferenceError: $ is not defined catergory.js:1 Even after following the suggested steps in this an ...

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...