Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call

function AjaxCallAndShowMessage(btnClick) {

$('form').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                ShowTimeChangeMessage(); // show an alert message
            }
        });

    return false;
});

}

// here is the view

<div id="dialog" title="">
@using (Html.BeginForm("Administration", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
@Html.DropDownList("SeTime", new List<SelectListItem>
{
new SelectListItem{ Text="1 Min", Value = "60" },
new SelectListItem{ Text="2 Min", Value = "120" },
new SelectListItem{ Text="3 Min", Value = "180" },
}, "Select Time")
<input type="submit" value="Set Time "  
onclick="AjaxCallAndShowMessage(this)" />
}
</div>

I am unable to retrieve data for the selected item from the dropdown list "SetTime" in the controller. Can someone provide guidance on how to appropriately make the AJAX call for this view? Thank you.

Answer №1

Your script will create a SELECT element named SeTime. When the form is submitted (via ajax or normal submission), the browser will send the selected option's value as the value of the form item with the key SeTime. This should function properly if you have a parameter with the same name in your HTTP post action method.

[HttpPost]
public ActionResult Administration(string SeTime)
{
 // to do : Do something with SeTime
 // to do : Return something
}

If you are utilizing a view model as the method parameter, ensure it is settable so that the model binder can assign the value from the posted form request.

public class YourViewModel
{
  public string SeTime {set;get;}
  // other properties here
}

Additonally, there seems to be a minor issue in your UI code. With your current implementation, when the user clicks the submit button, it triggers the AjaxCallAndShowMessage JavaScript function, which attaches a submit event handler to the form. Consequently, on subsequent clicks, additional event handlers get registered to the form resulting in multiple Ajax calls being made. To fix this, simply register the event handler once. Remove the onclick attribute from the HTML markup and instead use unobtrusive JavaScript like below:

<input type="submit" value="Set Time "   />

Then, register the submit event handler within the document ready event:

$(function () {

    $('form').submit(function () {

        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
               alert("Ajax call is done");
            }
        });

        return false;
    });
});

Answer №2

Why use jquery and ajax to submit a form when you can utilize @Ajax.BeginForm? This method functions similarly to a jquery ajax call, allowing the form to be posted without refreshing the page.

<div id="dialog" title="">
@using (Ajax.BeginForm("Administration", "Home", new AjaxOptions
                {
                    OnSuccess = "OnSuccess",
                    OnFailure = "OnFailure",
                    LoadingElementId = "progress"
                }))
     {

      @Html.DropDownList("SeTime", new List<SelectListItem>
        {
         new SelectListItem{ Text="1 Min", Value = "60" },
         new SelectListItem{ Text="2 Min", Value = "120" },
         new SelectListItem{ Text="3 Min", Value = "180" },
         }, "Select Time")
       <input type="submit" value="Set Time" />
      }
     }

 </div>

For further details, visit this link

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

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

Insert information into a nested array using Mongoose

I'm encountering an issue with my code, even though I know it may be a duplicate. Here is the snippet causing me trouble: exports.addTechnologyPost = function(req, res){ console.log(req.params.name); var query = { name: 'test ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Exploring the magic of Hover effects using CSS and JQuery

I am exploring ways to enhance the display of an element when hovering over it. I have implemented a button and my objective is for the first click to activate the hover effect, while the second click will reset it. However, I am facing an issue where the ...

Tips for isolating all the Javascript loaded via ajax or jquery.load within a specific child scope instead of a global scope

I am currently working on a solution to embed a third-party page into my site using ajax/jquery.load() to avoid using iframes (CORS requirements are already handled by the third party). My dilemma lies in the fact that the main host site loads jquery 1.x ...

Displaying two separate divs on a single jQuery mobile website using jQuery Ajax

In college, I was assigned a challenging project by the instructor that involved dynamically loading a multi-page jQuery mobile site using jQuery Ajax XML parser. The task included first populating an unordered list with list items from an xml file to be u ...

Unable to dynamically validate the input field for the name using Angular.js

Can someone assist me with an issue I'm having? I'm encountering an error while trying to dynamically validate input fields using Angular.js. Error: TypeError: Cannot read property '$invalid' of undefined Let me explain the code t ...

What is the process for reverting back to a previous version using n (Node Version Manager)?

After installing n(tj/n) to manage my node versions, I installed Node version 14.6 which automatically became the active version. When I tried to switch back using the n command, it only displayed the version I installed with n. Is there a way to switch b ...

Handling exceptions in Node.js is an essential part of writing reliable

Just a quick question: I seem to be dealing with an incorrect endpoint, and every time I run the code below, it results in an exception being thrown client.post("http://WrongEndPoint", [], function (data, response) { console.log("data:", data, "respo ...

There seems to be an issue with Material UI Autocomplete not responding to the onChange value

I am currently developing a project using reactjs and incorporating material ui to create components. One specific component I have utilized is the Autocomplete within a form for event creation in my project. I am encountering an issue where I want the sta ...

Nodejs Websocket integration with the Firefox browser

Currently, I am utilizing Aurora 17 along with Chrome 22 and Firefox 16 in order to develop a basic chat application. My server-side technology is Node 0.8.9. The issue I am experiencing pertains specifically to Firefox, as it fails to establish a connect ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

Unable to send information to a function (using jQuery)

I'm struggling to pass the result successfully to another function, as it keeps returning an undefined value: function tagCustomer(email, tags) { var o = new Object(); o.tags = tags; o.email = email; o.current_tags = getCustomerTags(email ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

Key within square brackets in a JSON array

I am dealing with a JSON array that includes a square bracket in the key, like this: { "msg":"OK", "data":[ { "nls!type":"NCR", "current":"Assign", "physicalid":"0FFE0001000009FC5BD6805C00001352", "attribute[custTitle]":"Tit ...

When attempting to navigate to a different page in Next.js, the Cypress visit functionality may not function as

In my upcoming application, there are two main pages: Login and Cars. On the Cars page, users can click on a specific car to view more details about it. The URL format is as follows: /cars for the general cars page and /cars/car-id for the individual car p ...

Guide for leveraging AngularJS for efficiently loading content within a collapsible panel

I'm currently working on an application that utilizes the Bootstrap Collapse component to display a series of collapsible panels, all starting in the closed position. Considering that there could be numerous panels on the page and each panel might ha ...

What is the best way to retrieve all collections and their respective documents in Firestore using cloud functions?

Seeking to retrieve an array structured as [1year, 1month, etc] with each containing arrays of documents. Currently encountering a challenge where the returned array is empty despite correct snapshot sizes. Unsure if issue lies with push() method implemen ...

A step-by-step guide on leveraging useRef() to specifically target dynamic material-ui tabs

When attempting to upload files to a specific channel, they always end up being uploaded to the first tab or channel. I've been using useRef to try and fix this issue, but I'm not sure what exactly is missing. By "tab," I am referring to the tab ...