Using Jquery Ajax to Send Data with ASP Core ActionResult

Is there a way to successfully submit a form data using Jquery Ajax in Asp Core?

AJAX CODE

    if (contactForm.valid() == true) {
    var formData = new FormData();
    formData.append("Name", contactForm.find("input[name='Name']").val());
    formData.append("Email", contactForm.find("input[name='Email']").val());
    formData.append("Subject", contactForm.find("input[name='Subject']").val());
    formData.append("Message", contactForm.find("textarea[name='Message']").val());
    $.ajax({
        url: "/home/contact",
        method: 'POST',
        data: formData,
        processData: false,
    }).done(function (data) {
        if (data == "success") {
            setTimeout(function () { $("#footer_contact__form .alert-success").removeClass("d-none") }, 500);
        }
        else {
            setTimeout(function () { $("#footer_contact__form .alert-danger").removeClass("d-none") }, 500);
        }
    }).fail(function () {

    });
}

CONTROLLER

 [HttpPost]
    public JsonResult Contact(Contact entity)
    {
        if (ModelState.IsValid)
        {
            entity.Date = DateTime.Now;
            _uow.Contact.Add(entity);
            return Json("ok");
        }
        else
        {
            return Json("failed");
        }
    }

I am encountering errors while attempting this. Can you provide guidance on how to effectively send a model with Asp Core and Ajax? Thank you.

Answer №1

Make sure to disable the contentType option.

$.ajax({
    url: "/home/contact",
    method: 'POST',
    data: formData,
    processData: false,
    contentType:false,
})

To learn more, check out this discussion.

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

Looking for someone to break down this Typescript code snippet for me

As a Javascript developer, I am currently diving into an unfamiliar TypeScript code block within a project. Here is the code snippet: ViewModel newPropertyAddress = new ViewModel(){name, previousPro = oldValue } ...

Adding a div via an Ajax call is only successful during the initial page load

Currently, I am utilizing a combination of YQL and jQuery to retrieve content from a distant page. While I am able to successfully load the content during the initial page load, I encounter an issue when attempting to return to the same page after navigati ...

Troubles with displaying information retrieved using useEffect within a personalized hook

Delving into the world of React and utilizing React hooks as a beginner can be both exciting and challenging. I've come across a scenario where I'm working with a function component that is responsible for displaying information on the page. Whil ...

When initializing a local scope property as null in Angular.js, it may end up being undefined

Recently, I created a custom Angular directive. <location zipcode="35423" cityname="" statecode=""></location> Within the directive, I defined the following: scope: { zipcode: "@", cityname: "@", ...

What is the purpose of the code snippet 'jQuery.each(lines, function(lineNo, line)'?

As a newbie to jquery and ajax, I stumbled upon some code online that caught my attention. The code snippet below prompted me to question its purpose and functionality: lines = newLine.split('#'); jQuery.each(lines, function(lineNo, line) ...

Using AJAX to post button values

I have encountered an issue while attempting to post a value to a PHP script using the POST method in AJAX. The error message is as follows: Notice: Undefined index: gamekey Here is the JavaScript code I am working with: function adminchat(row) { ...

Guide on implementing a looping settimeout function on a sliding page to dynamically load an HTML template within the Framework 7 framework

My current setup involves using Framework7 (framework7.io). The code below functions correctly on the main view page, utilizing a looping settimeout to refresh signups.html every second: <script type=“text/javascript” src=“code.jquery.com/jquery- ...

The deployment of the next.js error on Vercel was successful ✓ All five static pages were generated without any issues. However, there was an error encountered during the export process specifically in the

I'm having trouble deploying a next.js + mongodb project to Vercel. Every time I try, I encounter this error: Error occurred prerendering page "/products". Read more: https://nextjs.org/docs/messages/prerender-error SyntaxError: Unexpected t ...

Tips for refreshing CSS following an ajax request

Currently, I am facing an issue with the CSS formatting on my page. I am using Django endless pagination to load content on page scroll. However, when new content is loaded, the CSS applied to the page does not work properly and needs to be refreshed. Can ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

What is the best way to apply dynamic wrapping of a substring with a component in Vue.js?

My Objective My goal is to take a user input string and render it with specific substrings wrapped in a component. Specifically, I am looking to identify dates within the string using a regex pattern and then wrap these dates in a Vuetify chip. Progress ...

What is the reason behind this being deemed as true?

Imagine we have this snippet of code: var attachRed = false; Why is attachRed = !attachRed equivalent to true? I'm curious because I'm working with Vue.js and trying to grasp why this particular piece of code functions as it does. <div id= ...

This element is not compatible for use as a JSX component

I have created a React component which looks like this import React from 'react'; import { ECOTileSummary } from './ECOTileSummary'; import { TileSummary } from './TileSummary'; interface SuperTileSummaryProps { date?: s ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...

What is the reason for Firefox displaying the "excessive recursion" error message?

I have been working on generating an area Google chart using the code below, but I am running into an issue where Firefox is showing me a "too much recursion" error. The chart currently only has one point for testing purposes. Can anyone provide some gui ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...

Auto-fit HTML Webpage Resizer Simplified

Just finished my very first jQuery project, a simple full-width slider. I've been focusing on HTML & CSS and currently working with C#. The problem is that I don't want the page to be scrollable; I want it to autofit to the webpage. Imagine ope ...

Issue with Ajax and Laravel 500 (Server-side Quandary)

I'm having trouble with using AJAX in Chrome. Below is the code snippet from my web.php file: Route::view('menu','home.menu',['categories'=> App\Categories::orderBy('name')->get()->take(11),'a ...

I am struggling to retrieve the data from the Giphy API after making the initial AJAX request

I'm currently in the process of building a basic website that fetches random gifs from the Giphy API. This project is purely for practice, so I'm keeping the site very minimalistic. However, I've hit a snag when it comes to extracting data u ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...