The JSON object was posted with a value of null instead of the intended object

When I utilize a literal stringified JSON object, everything runs smoothly as anticipated

Index.cshtml (with literal ajax string $.ajax OPERATES)

var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';

var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
    url: '/api/auditApi',
    type: "Post",
    contentType: "application/json; charset=utf-8",
    data: '{\'Thing1\':\'42\',\'Thing2\':\'43\',\'Thing3\':\'44\'}',
    dataType: 'json',
    success: function (result) {
                       $(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
                       $(".kendoAudit").data("kendoGrid").dataSource.read();
                       $(".kendoAudit").data("kendoGrid").refresh();
                   },
                   error: function (xhr, ajaxOptions, thrownError) {
                       alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
                   }
               });

However, when I opt for a serialized object generated inline, it receives null passed into the post handler

Index.cshtml (with object created inline and sent to $.ajax FAILS)

var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';

var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
    url: '/api/auditApi',
    type: "Post",
    contentType: "application/json; charset=utf-8",
    data: searchSerialized,  //I have tried concatenating with + '' also
    dataType: 'json',
    success: function (result) {
                       $(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
                       $(".kendoAudit").data("kendoGrid").dataSource.read();
                       $(".kendoAudit").data("kendoGrid").refresh();
                   },
                   error: function (xhr, ajaxOptions, thrownError) {
                       alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
                   }
               });

Controller

public HttpResponseMessage Post([FromBody]string value)
{
    try
    {
        var results = JsonConvert.DeserializeObject<dynamic>(value);
    }
    catch (Exception ex) 
    {
        // throws because value is null.
    }
}

I am certain that there must be something glaringly obvious that I am overlooking in this conversion process.

The debug line: alert(searchSerialized); showcases the expected output

Answer №1

By fetching the data directly into the model, you can simplify the process. When a serialized object is posted (no longer as a string), MVC will automatically bind it to the appropriate model.

Consider updating your action method like this.

    public class FilterObject
    {
        public int Item1 { get; set; }
        public int Item2 { get; set; }
        public int Item3 { get; set; }
    }

    [HttpPost]
    public ActionResult Example(FilterObject filterObject)
    {
        return View();
    }

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

Is it possible to use traditional form submission after dynamically adding an HTML control with JQuery?

I just need some clarification! If I have added an HTML control (input, dropdown, etc.) after the page has loaded using jQuery, can I still submit a form using the traditional method (HTML submit button)? Or do I have to submit all HTML controls using an ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

What is the best method for eliminating the double quotes from the JSON data output?

I am currently developing a Windows Phone 7 application using Phonegap and I am working with web service data binding. The web service returns JSON format like the example below: LocationAddress: "85 Cowley Avenue, Hyderabad", This is my AJAX call: $.a ...

How to employ Proxy<T> with a type other than T as the parameter?

I find myself in a situation where I am interested in utilizing the Proxy feature to implement "load balancing" among a collection of classes. To illustrate my approach, consider the following simple example: class Foo { constructor(private msg: stri ...

Guide to formatting JSON correctly in Java

private List<String> itemsInCart = new ArrayList<>(); private List<String> itemObjectsInCart = new ArrayList<>(); @CrossOrigin @GetMapping(value = "/cartitems") public List<String> getItemsInCart(@RequestParam("buyerId") Int ...

Attempting to determine income in JavaScript with the inclusion of two distinct rates

Trying to come up with a salary calculation for different rates within the same timeframe is proving to be quite challenging. For instance, between 10:00-15:00 the rate is $20 per hour and from 15:00 onwards it drops to $15 per hour. Check out the entire ...

Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is ...

Unable to retrieve JSON information using AJAX

Trying to retrieve data from the server without refreshing the page using AJAX. The issue is that the data appears as text rather than in JSON format. Here is my code: $.ajax({ type: "GET", url: "http://localhost:8080/search?key=" + QUERY + "", ...

Choosing options from a drop-down menu based on the selection of a radio button with ever-changing

I have a dynamic form with fields retrieved from a database. This form features questions and answers. My goal is to display a number, such as 5, in a drop-down question based on the selected radio button for question 3 without needing to submit the form ...

Maintaining alignment of background elements and div images

I'm struggling to align images properly across different devices. It's more challenging than I anticipated. Currently, on mobile in portrait mode, the image is not displaying as I want it to. Ideally, I want it to be closer to how it looks in la ...

Struggle to link a string together effectively for proper concatenation

I'm currently working on a project that involves utilizing the Wikipedia API. My goal is to create a link for each list item, but I'm encountering difficulty with proper concatenation. Here's the code snippet I'm using: for (var j=0 ...

Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task For example, if I have the window.location.href, the URL might look like this: https://mypage/route/step-1/mor ...

Creating a homepage for a specific area in ASP MVC

I'm currently working on creating an index page for my admin area, but I'm struggling to figure it out. I've tried searching for a solution but haven't found anything helpful yet... Here is a visual representation of the area: https:/ ...

Is it possible to decode nested JSON into a flat structure?

Is it possible in Go to unmarshal nested json into a differently structured struct, such as flattening out the nesting? { "id":1, "person":{ "name": "Jack" "extra": { "age": 21 } } } type Item struct { ID int64 `json:"id"` ...

bootboxjs prompt type not recognized - the given example in the documentation is ineffective

I have been experimenting with the functionality of in my project. I started off by using their example code to test if it works. Following the guidelines provided, I have integrated the latest versions of bootstrap, jquery, and bootstrap js, along with ...

Unable to show additional tooltip information on the price history chart

In an attempt to enhance the tooltip of a price-history chart (stockChart), I am trying to display extra data. Here is a jsfiddle example: http://jsfiddle.net/z10dLcj8/1/ $(function(){ var priceHistoryObjArray = [ [1379883600000,47.19,'extra ...

Tips for retrieving the longest word from an array in JavaScript/JSON

I'm creating a custom function that will identify and extract the longest word from a given string. If there are multiple words of the same length, the function will return the first one it encounters. The function also disregards numbers and punctuat ...

Tips for monitoring a variable within a Service using a Controller to trigger a modal?

http://plnkr.co/edit/bdHiU0?p=preview When I require a variable that is returned by a service, like the data in InitTickersFactory.returnTickers(), I can easily assign it to vm.tickersObject. However, in the plnkr example provided above, I am simply toggl ...

Encountering an Uncaught TypeError occurs when attempting to access properties of undefined, specifically while utilizing an object method with arrays

I was studying how to destructure arrays from objects and expected the order function to return two values, but it did not. const restaurant = { name: 'Classico Italiano', location: 'Via Angelo Tavanti 23, Firenze, Italy', c ...

JavaScript: Link a function and a text to a common property identifier

While some may argue against it, I am intrigued by the process of executing this action. I have observed instances where typing a property name yields a value, but when followed by parentheses, it accesses a method. To illustrate visually: foo returns & ...