Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3347002
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T01:22:13+00:00 2026-05-18T01:22:13+00:00

Im trying to get a list of line items to a webpage using JSON,

  • 0

Im trying to get a list of line items to a webpage using JSON, which will then be manipulated and sent back to the server by ajax request using the same JSON structure that arrived (except having had a field values changed).

Receiving data from the server is easy, manipulation even easier! but sending that JSON data back to the server for saving… suicide time! PLEASE can someone help!

Javascript

var lineitems;

// get data from server
$.ajax({
    url: '/Controller/GetData/',
    success: function(data){
        lineitems = data;
    }
});

// post data to server
$.ajax({
    url: '/Controller/SaveData/',
    data: { incoming: lineitems }
});

C# – Objects

public class LineItem{
    public string reference;
    public int quantity;
    public decimal amount;
}

C# – Controller

public JsonResult GetData()
{
    IEnumerable<LineItem> lineItems = ... ; // a whole bunch of line items
    return Json(lineItems);
}

public JsonResult SaveData(IEnumerable<LineItem> incoming){
    foreach(LineItem item in incoming){
        // save some stuff
    }
    return Json(new { success = true, message = "Some message" });
}

The data arrives at the server as serialized post data. The automated model binder tries to bind IEnumerable<LineItem> incoming and surprisingly gets the resulting IEnumerable has the correct number of LineItems – it just doesnt populate them with data.

SOLUTION

Using answers from a number of sources, primarily djch on another stackoverflow post and BeRecursive below, I solved my problem using two main methods.

Server Side

The deserialiser below requires reference to System.Runtime.Serialization and using System.Runtime.Serialization.Json

private T Deserialise<T>(string json)
{
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serialiser = new DataContractJsonSerializer(typeof(T));
        return (T)serialiser.ReadObject(ms);
    }
}

public void Action(int id, string items){
    IEnumerable<LineItem> lineitems = Deserialise<IEnumerable<LineItem>>(items);
    // do whatever needs to be done - create, update, delete etc.
}

Client Side

It uses json.org’s stringify method, available in this dependecy https://github.com/douglascrockford/JSON-js/blob/master/json2.js (which is 2.5kb when minified)

$.ajax({
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T01:22:14+00:00Added an answer on May 18, 2026 at 1:22 am

    Take a look at Phil Haack’s post on model binding JSON data. The problem is that the default model binder doesn’t serialize JSON properly. You need some sort of ValueProvider OR you could write a custom model binder:

    using System.IO;
    using System.Web.Script.Serialization;
    
    public class JsonModelBinder : DefaultModelBinder {
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                if(!IsJSONRequest(controllerContext)) {
                    return base.BindModel(controllerContext, bindingContext);
                }
    
                // Get the JSON data that's been posted
                var request = controllerContext.HttpContext.Request;
                //in some setups there is something that already reads the input stream if content type = 'application/json', so seek to the begining
                request.InputStream.Seek(0, SeekOrigin.Begin);
                var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();
    
                // Use the built-in serializer to do the work for us
                return new JavaScriptSerializer()
                    .Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
    
                // -- REQUIRES .NET4
                // If you want to use the .NET4 version of this, change the target framework and uncomment the line below
                // and comment out the above return statement
                //return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
            }
    
            private static bool IsJSONRequest(ControllerContext controllerContext) {
                var contentType = controllerContext.HttpContext.Request.ContentType;
                return contentType.Contains("application/json");
            }
        }
    
    public static class JavaScriptSerializerExt {
            public static object Deserialize(this JavaScriptSerializer serializer, string input, Type objType) {
                var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
    
                // internal static method to do the work for us
                //Deserialize(this, input, null, this.RecursionLimit);
    
                return deserializerMethod.Invoke(serializer,
                    new object[] { serializer, input, objType, serializer.RecursionLimit });
            }
        }
    

    And tell MVC to use it in your Global.asax file:

    ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
    

    Also, this code makes use of the content type = ‘application/json’ so make sure you set that in jquery like so:

    $.ajax({
        dataType: "json",
        contentType: "application/json",            
        type: 'POST',
        url: '/Controller/Action',
        data: { 'items': JSON.stringify(lineItems), 'id': documentId }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Just trying to get my irb sessions to actually list the current line of
I am trying to get a list of subdirectories in a given directory using
I'm trying to use templates to get std:list of items, where each item has
I'm trying to get two-column typesetting working, with a list of items. However, that
I'm trying to get a class memeber variable list at run time. I know
I'm trying get values from a GridView using the following code: foreach (GridViewRow row
Trying to get an ASP application deployed; it worked for a while but then
I'm trying to read a list of items from a text file and format
I'm trying to get a block of code down to one line. I need
Trying to get my css / C# functions to look like this: body {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.