Sending JSON Data to ASP.NET MVC: A Custom Model Binder Solution

Dec 07, 2025 · Programming · 12 views · 7.8

Keywords: ASP.NET MVC | JSON | Ajax | Model Binder | Custom Binder

Abstract: This article explores the challenges of sending JSON data from client to server in ASP.NET MVC applications. It focuses on the issue where the default model binder fails to deserialize JSON payloads correctly, resulting in objects with empty properties. Based on the accepted StackOverflow answer, it details the implementation of a custom JsonModelBinder, including server-side code and client-side Ajax configurations, with additional insights from other answers for a comprehensive technical overview.

Problem Background

In ASP.NET MVC development, using JSON for data exchange between client and server is common. However, when sending JSON data back to the server, the default model binder often fails to deserialize it properly, leading to objects with the correct count but empty properties. This stems from the default binder being designed for form data, not raw JSON payloads.

Limitations of the Default Model Binder

The default model binder in ASP.NET MVC treats JSON data as a string when received via Ajax, lacking built-in support for JSON format deserialization into strongly-typed objects. This causes binding failures, as the binder does not automatically parse the JSON structure.

Implementation of a Custom JsonModelBinder

To address this, a custom model binder can be created. Key steps involve checking if the request's Content-Type is application/json and then deserializing the JSON string using a serializer like JavaScriptSerializer. Below is a simplified code example based on the best answer:

using System.IO;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class JsonModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        if (request.ContentType != null && request.ContentType.Contains("application/json"))
        {
            request.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonString = new StreamReader(request.InputStream).ReadToEnd();
            return new JavaScriptSerializer().Deserialize(jsonString, bindingContext.ModelMetadata.ModelType);
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

Register this binder in Global.asax:

ModelBinders.Binders.DefaultBinder = new JsonModelBinder();

Client-Side Configuration

On the client side, when sending Ajax requests with jQuery, it is essential to set contentType to "application/json" and dataType to "json", and serialize data using JSON.stringify. Example code:

$.ajax({
    type: 'POST',
    url: '/Controller/SaveData',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(lineItems) // lineItems is the JSON object
});

Alternative Approaches and Supplements

Other answers suggest using the built-in JsonValueProviderFactory available in MVC3 and later, which simplifies the process by adding a value provider factory. Additionally, some developers prefer writing custom ValueProviderFactory or using jQuery plugins to format data compatibly with the default binder. These methods offer flexibility, but the custom model binder is a robust solution for earlier MVC versions.

Conclusion

Implementing a custom JsonModelBinder is an effective way to handle JSON data binding in ASP.NET MVC. By combining server-side binder adjustments with proper client-side Ajax settings, developers can seamlessly send and receive JSON data, ensuring model binding works correctly and enhancing data manipulation efficiency in web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.