Accept JSON data in ASP.NET MVC action method for posting data

I have a model class named Parcel which contains the parameters Name and CenterPoint:

public class Parcel
{
    public string Name { get; set; }
    public object CenterPoint { get; set; }
}

The values for these parameters are obtained from a map. When a parcel is clicked, the center point is calculated and stored in a JavaScript variable. The CenterPoint is represented as a JSON object, while the Name is plain text.

I need to save the CenterPoint as a JSON object in the database so that it can be retrieved and drawn on the map later.

However, when I post the data to the action method as shown below, the CenterPoint object appears as {object}:

It should actually look like this: { type="point", x=121.32380004076, y=452.024614968}

    [HttpPost]
    public ActionResult SaveParcel(Parcel parcel)
    {
        return Json(new {parcel}, JsonRequestBehavior.AllowGet);
    }

My JavaScript code snippet is here:

           var postData = {
                    "Name": document.getElementById("name").value,
                    "CenterPoint": document.getElementById("center").value
            };

            $http({
                method: 'POST',
                url: "/Parcel/SaveParcel/",
                data: postData,
            }).success(function (data, status, headers, config) {
                console.log(data);
            });

I am looking for a way to store and retrieve the JSON data accurately. Is there a better approach available?

Answer №1

Is it possible for a JSON deserializer to convert your Point to an anonymous class, and place it inside a generic Object property? From what I know, the answer is no. You can check out this post for more details along with a solution if absolutely necessary.

If you create a Location class like this:

public class Location
{
    public type { get; set; }
    public float x { get; set; }
    public float y { get; set; }
}

You can then modify Parcel as follows:

public class Parcel
{
    public string Name { get; set; }
    public Location CenterPoint { get; set; }
}

Keep in mind the requirement of placing the object inside a generic Object property. The deserializer may not perform this task, but using Json.NET can serve the purpose for handling a dynamic object. In that case, you could update your Parcel class to:

public class Parcel
{
    public string Name { get; set; }
    public dynamic CenterPoint { get; set; }
}

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

Tips for ensuring the security of your code in node.js

Here is a snippet from my app.js that deals with managing connections: var connections = []; function removeConnection(res) { var i = connections.indexOf(res); if (i !== -1) { connections.splice(i, 1); } } I make a call to removeConn ...

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

Transforming JSON data into an Angular TypeScript object

Delving into the realm of Angular on my own has been quite an enlightening journey, but I'm currently facing a specific issue: My aim is to create a website using both Spring for the back end and Angular 7 for the front end. However, I've encoun ...

Error: The object cannot be serialized to JSON

I am attempting to append a string of Python dictionary to Google Sheets Here is the code I have: SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' SPREADSHEET_ID = 'XXX' RANGE_NAME = 'Sheet1!A2:F2' now = time ...

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

How can we process the incoming data that is in a JSON format?

I'm in the process of creating a Zap that collects customer feedback through Unbird and delivers a coherent Slack message that can be easily understood by anyone within my organization. When importing customer feedback data from Unbird into Zapier, i ...

Gson - The issue with my JSON file caused by the loop

My "example.json" file looks like this before I execute my code: { "example1": { "example2": { "example3": 30 } } } After running the following code: JsonManager.writeString("example", "example1", "example2", "example7", "70"); This fun ...

Sending a second request with jQuery to upload a file

After successfully uploading a file using jQuery AJAX along with a progress bar (XHR), the next step involves processing the uploaded file on the server side. To check the status of this server-side processing, I attempt to make another jQuery AJAX request ...

Considering an attempt to remove a data entry from a table using AngularJS, node.js, and mongoDB

Can anyone help figure out why this isn't working as expected? $scope.removeProduct = function(product){ console.log(product._id); $http.delete("/api/products/" + product._id) .success(function (data) { ...

Tips and tricks for storing and retrieving form state using local storage with jQuery in JavaScript

I'm trying to save the form state in localstorage, I am able to save it successfully but I'm encountering an issue where I am unable to save the input typed data Desired outcome: If I type doggy inside the input box, I want that value to be ret ...

Is it true that echo and print are disabled in the 'real-time' version of php?

As a newcomer to programming, I can only describe my script as live, although I know that might not be the correct term. Initially, I developed a bot in php and ran it on xampp locally on my mac, where I could easily print arrays and other content using ec ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

Sinon experiences delays during an AJAX call

I am working with Mocha Chai and Sinon to test a revealing module pattern and encountering a timeout failure. How can I effectively test a method that assigns variables from an AJAX request? Test.js (function () { 'use strict'; describe(&a ...

Fetching JSON data through AJAX call from PHP file

I seem to be having trouble accessing the data inside the javascript, even though everything appears to be in order. I know there are plenty of tutorials available, but I'm feeling a bit confused. Can someone offer me some assistance? Here are three ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

Invoke a REST endpoint using Mockito

When my server is deployed, I have a Rest function in Jersey that returns a JSON string: @GET @Path("getallemployees") @Produces("application/json") public Response getAllEmployees() { //building the entity object which is List<Employee> return Resp ...

How to Access a Method from Controller 2 in AngularJS Controller One

angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { // Code for controller1 function } }) .controller('controller2',fun ...