The issue of empty strings not converting to null when passing a JSON object to a controller

My observation in ASP.NET Core 2.1 is quite the opposite of a similar question raised about string.empty being converted to null when passing JSON object to MVC Controller.

In my case, when a JSON object with properties containing empty strings is sent back to a controller, they are not automatically converted to null anymore.

For instance, consider this JavaScript object:

 var person = {firstName:"", lastName:""}; 

        $http.post("/app/index", person)
            .then(function (response) {
                // Success
            }, function (error) {
                // Failure
            })

Upon binding to the model in the controller, the properties with empty strings remain as such:

    //
    // POST: /App
    [HttpPost]
    public async Task<ActionResult> Index([FromBody] AppFormDTO data)
    {
       ....
    }

When attempting to save this object in the database, it would be preferable to have null values instead of numerous empty strings.

Has there been a change to the DefaultModelBinder in ASP.NET Core 2.1? If so, how can I revert it back to the behavior in MVC5 where string.empty was automatically converted to null?

UPDATE, including my AppFormDTO model for reference:

public class AppFormDTO
{
    public string firstName{ get; set; }
    public string lastName{ get; set; }
}

Answer №1

To enhance your PERSON model with firstName/lastName, make sure to include the following:

[DisplayFormat(ConvertEmptyStringToNull = false)]
... insert the model values here 

Answer №2

Exploring the source code of ASP.NET Core framework

 if (bindingContext.ModelType == typeof(string))
 {
      // If the model is already a string, no further conversion is needed but it will handle ConvertEmptyStringToNull.
      if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && string.IsNullOrWhiteSpace(value))
      {
           model = null;
      }
      else
      {
           model = value;
      }
 }

By default, the behavior is set to convert empty strings to null. Make sure to check your model AppFormDTO if you have incorrectly set ConvertEmptyStringToNull = false.

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

Using Jquery Chosen Plugin to Dynamically Populate One Chosen Selection Based on Another

Good evening to all, please excuse any errors in my English. I have successfully integrated a jQuery Chosen plugin with my 'estado' field (or province). My goal is to populate another jQuery Chosen plugin with the cities corresponding to that s ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Are cookies always included in client requests?

With every interaction between the server and browser, cookies are exchanged back and forth. However, what happens when an image is requested? <img src='myPic.jpg' /> Is the browser also sending cookies during this type of request? If i ...

Effortlessly sending multiple forms on a single page via POST in Express JS without the need for page refresh

I am creating a new application using ExpressJS and I want to include the following HTML code in a jade file. On one of my pages, I have 4 form buttons: <div class="dog"> <div class="dog_wrapper clearfix"> <div cla ...

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

Display Binary Image in HTML Table using Server-side Code

I am currently working on creating a table that will retrieve binary image data from a database and display it in an HTML table. Here is the markup I have used: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml1 ...

Are you familiar with PowerShell and its innovative modular GUI capabilities?

One challenge I face is assisting clients who constantly monitor the performance of their servers, services, and network. Utilizing PowerShell, I envisioned creating a unified GUI interface for all these tasks, including remote log tailing capabilities. B ...

Refreshing Django HTML table dynamically upon database updates

Currently, I have an HTML table set up using a Django template to showcase data from my database. I am looking to ensure that this table remains updated in real-time whenever the database undergoes changes. Despite my research efforts, there is limited inf ...

Use jQuery.ajax() to submit data in separate rows of a table

At the moment, I have no issues submitting my form as long as it contains only one row in the table. However, when I add a second row, an error occurs and the submission fails. My goal is to be able to post the data from each table row separately with just ...

Trouble displaying data with Angular 6 JSON object pipe

Having an issue with displaying tasks from a MongoDB project schema in HTML. The tasks are stored in a nested array and I want to show the task name and description. Here's the code: <div class="card-body"> {{project.taskName | json}} </ ...

Transform input string containing newline characters into separate paragraphs

I utilize Contentful CMS for content management and fetch the content through their API. When the content is fetched, it comes in as a JSON object. One of the keys within this object pertains to the main text block for the entry I am retrieving. This stri ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...

Extracting Data from JSON Using Vue.js

I am facing an issue with extracting data from a JSON file using Vue.js. Below is the HTML and JSON data along with the script. Any help would be appreciated. <!DOCTYPE html> <html> <head> <title>Vu ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

Retrieve information from an HTML form

Currently, I have a piece of Javascript that fetches the HTML for a form from the server using an XMLHttpRequest and then displays the form on the page. I am looking for a solution to extract the data that would be sent via POST if the form were submitted ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...