how can i send form data(MVC) with some other values(other field values i.e.(update button text values) fetched using jquery) using ajax post request. i have tried alot also searched alot but nothing found.please help me in it
i want to use above approach for a single MVc action result
e.g. if updatevalue not null update the record otherwise add the record
To send form data along with additional parameters using an AJAX POST request in an ASP.NET MVC application, you can follow these steps:
$.ajax
Gather Form Data and Additional Parameters Using jQuery:
$('#submitButton').on('click', function() { // Gather form data var formData = new FormData($('#myForm')[0]); // Additional parameters var updateValue = $('#submitButton').text(); // or any other way you get this value formData.append('updateValue', updateValue); // AJAX POST request $.ajax({ url: '/YourController/YourActionMethod', type: 'POST', data: formData, processData: false, contentType: false, success: function(response) { // Handle success console.log('Success:', response); }, error: function(xhr, status, error) { // Handle error console.log('Error:', error); } }); });
Configure Your MVC Controller:
public class YourController : Controller { [HttpPost] public ActionResult YourActionMethod(string name, string email, string updateValue) { if (!string.IsNullOrEmpty(updateValue)) { // Update record logic } else { // Add record logic } // Return a response return Json(new { success = true, message = "Operation completed successfully." }); } }
<form id="myForm"> <!-- Your form fields here --> <input type="text" name="name" id="name"> <input type="text" name="email" id="email"> <input type="submit" value="Update" id="updateBtn"> </form>
$(document).ready(function() { $('#myForm').submit(function(e) { e.preventDefault(); // Prevent default form submission // Get form data var formData = $(this).serializeArray(); // Get additional values using jQuery var updateValue = $('#updateBtn').val(); // Assuming update button text is the value // Add additional value to form data formData.push({name: 'updateValue', value: updateValue}); // Send AJAX POST request $.ajax({ url: '/YourController/YourAction', type: 'POST', data: formData, success: function(response) { // Handle success console.log(response); }, error: function(xhr, status, error) { // Handle error console.error(xhr.responseText); } }); }); });