Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Send JSON data via POST (ajax) and receive json response from Controller (MVC)

How to Send and Receive JSON Data via POST (Ajax) in MVC Controller

Are you struggling with sending JSON data via POST and receiving a JSON response from your MVC Controller? Don't worry, I've got you covered. In this guide, I'll walk you through the common issues you might encounter and provide easy solutions. So let's dive in!

The Problem: sendInfo Becomes Null in the Controller Action

In your JavaScript function, you're trying to send JSON data to the controller, but the sendInfo becomes null in the controller action. Let's see what could be causing this.

The Solution: Proper Model Binding and Data Type

To fix this issue, you need to ensure that the model binding works correctly and that the data types match between the JavaScript object and the server-side model.

  1. Specify the Request Content Type: In your JavaScript $.ajax call, add contentType: "application/json" to specify the content type as JSON.

$.ajax({
    type: "POST",
    url: "/Home/Add",
    dataType: "json",
    contentType: "application/json", // Add this line
    success: function (msg) {
        // ...
    },
    data: JSON.stringify(sendInfo) // Stringify the JSON object
});
  1. Declare Properties as Public in the Model: In your PersonSheets model, make sure to declare the properties as public. This is essential for proper model binding.

public struct PersonSheets
{
    public int Id { get; set; } // Add get and set
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}
  1. Use [FromBody] Attribute: In your controller action, use the [FromBody] attribute to specify that the data is coming from the request body.

[HttpPost]
public ActionResult Add([FromBody] PersonSheets sendInfo) // Use [FromBody] attribute
{
    // ...
}

By following these steps, you should now be able to send the JSON data successfully to the controller and ensure that sendInfo is not null.

Sending Back a JSON Response

You also mentioned sending back a response to AJAX via JSON. Yes, it is possible! In the controller action, you can return a JSON object using the Json method. Here's an example:

[HttpPost]
public ActionResult Add([FromBody] PersonSheets sendInfo)
{
    bool success = _addSomethingInList.AddNewSomething(sendInfo);

    return this.Json(new { msg = success });
}

In the JavaScript success function of your AJAX call, you can access the response JSON like this:

success: function (msg) {
    if (msg) {
        // Success logic
    } else {
        // Error logic
    }
}

Conclusion: You're Ready to Send and Receive JSON Data in MVC

Congratulations! 🎉 You've learned how to send JSON data via POST (Ajax) and receive a JSON response from your MVC Controller. Remember to ensure proper model binding, specify the content type, and use the [FromBody] attribute. Plus, don't forget that you can send back the response to AJAX using JSON.

Now it's time to give it a try in your project. Don't hesitate to leave any questions or comments below. Happy coding! 💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my