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

The toggle checkbox feature in AngularJS seems to be malfunctioning as it is constantly stuck in the "off"

I am trying to display the on and off status based on a scope variable. However, it always shows as off, even when it should be on or checked. In the console window, it shows as checked, but on the toggle button it displays as off Here is the HTML code: ...

I'm curious if it is possible to retrieve the dates of actions on websites using Selenium with Python

Is there a way to retrieve the date of data, like the date of comments, using HTML codes? I need assistance on how to achieve this through selenium in Python. Can Jquery be used as a solution? ...

Repeater employs Endless Scrolling feature within DotNetNuke

I've integrated DotNetNuke into my custom module and I'm following the standard ASP.NET programming techniques (dragging/dropping). The project involves a posting service that uses a repeater with infinite scrolling and a masonry effect. I have f ...

The alignment of the timeline in HTML CSS becomes distorted once it reaches the fourth element

As a newcomer to HTML, CSS, and JS, I am currently embarking on the task of creating a personal website for a course project. One of the pages on my website showcases a timeline featuring dates and information. While I have referred to a tutorial on W3scho ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

Organize tabs with ease in the bootstrap-tabdrop plugin

My webpage features a navigation bar along with the bootstrap-tabdrop plugin, which places tabs in a dropdown menu if there are too many to display on one line. The main objective is: No action when navigating through currently displayed tabs. Clicking o ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Utilize AngularJS to inject a service into a module without assigning it to a variable, enabling easier minification

Currently, I am attempting to decrease the size of my AngularJS JavaScript code (using SquishIt). Within my module, there is a service injected as a function argument, as shown below. var myapp = angular.module('myapp', ['ngSanitize'] ...

What is the best way to mention @here with an attachment?

I'm attempting to use the canvas say command to display an image with an @here mention included, but unfortunately it only shows the image without making the mention. Below is what I have attempted: message.channel.send(`@here\n`+attachment); ...

Tips for executing a right slide animation in Jquery

I used a div class to create an arrow symbol >>. On click, I would like the list of items to slide in from left to right and pause for 20 seconds. When clicked again, it should slide back to the left and disappear. I attempted this using Jquery but ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Is it possible for a form to direct submissions to various pages depending on the value of certain fields

I need to set up a text field and submit button that will redirect users based on their input: index.html: If the user inputs "123" in the text box and clicks submit, they should be redirected to john.html page. AND If the user inputs "456" and clicks s ...

Activating a inaccessible element

Attempting to enable a disabled element upon clicking a P element, the following code snippet demonstrates storing a value from one textbox into another. The appended div contains a subsequent textbox which will be disabled. On mouseover of the div, option ...

Display JSON data values using jQuery

After receiving my data from Json, I am having trouble displaying it. Below is the javascript code snippet: jQuery( document ).ready( function( $ ) { $('select[name="country_id"]').on('change', function() { $.ajaxSetup({ ...

Don't forget to retain the checkboxes that were chosen in the

I am looking for a solution to a specific scenario. When I open a modal box and check some checkboxes, I want those same checkboxes to be selected the next time I open it. Below is an example of my code. Main Controller modal function function openModa ...

Node.Js error: "The requested resource does not have the 'Access-Control-Allow-Origin' header present."

This particular query shares similarities with others, however there is a perplexing difference that is causing it to malfunction. Previously, my JavaScript was able to fetch 6 json files without any issues. In Node.JS, I have configured cors and headers ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

What is the correct way to establish an array variable containing objects?

What is the correct way to declare an object within an array variable? I encountered the following error message: "TypeError: Cannot set property 'name' of undefined" Here is the code snippet in question: let data = [] data[0].name = "john" ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...