submit a JSON object using a form in C# MVC

I'm attempting to transmit a JSON serialized object via a form to a C# MVC action.

var obj = {
  id: 1,
  field1: "",
  field2: "",
  .
  .
  .
}

var inputs = "<input type'hidden' name='serializedObject' value='" + JSON.stringify(obj) + "'/>";
$("<form action='actionUrl' method='POST' >" + inputs  + "</form>").appendTo("body").submit().remove();

On the server side, I have an action that receives and parses the stringified object:

[HttpPost]
public virtual FileResult TestAction(string serializedObject){
    //...do stuff....
}

However, in the action, I am not receiving the full JSON string (I must use a form and not AJAX because I need to download a file).

Answer №1

It's possible that the issue you're experiencing is due to single quotes in your data values. If a value contains a single quote, anything after it may not be sent as single quotes are not considered valid.

To avoid this problem, it is recommended to surround all fields and values with double quotes.

For example, when I sent an object like this:

var object = {
            "id": "1",
            "field1": "Its",
            "field2": "working",
            "field3": "Fine!"
        }

The full object was successfully received:

{"id":"1","field1":"Its","field2":"working","field3":"Fine!"}

However, sending an object like this:

var object = {
                "id": "1",
                "field1": "It's",
                "field2": "working",
                "field3": "Fine!"
            }

Resulted in incomplete values being received:

{"id":"1","field1":"It

An alternative solution is to replace the single quotes with &#39 ("field1": "It&#39s",) which has been shown to work as well.

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

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Creating a flexible connection between a collection of textboxes and a model consisting of strings

In my current view model, I have a single property that is a list of team names: public List<string> TeamNames = new List<string>(); When the user accesses the form, they are initially presented with only one textbox for entering a team name. ...

How can you effectively update the content of a Parent component in react-native by communicating with its child component?

In one of my child components, I have included a button for interaction. Now, within my Parent component, I have three of these child components arranged side by side. Whenever any of these child components are clicked/touched, I want to trigger changes ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Utilize a React Hook that fetches data from an API upon clicking two distinct buttons

I have developed a next.js application integrated with mongoDB as the database. Currently, there are two buttons in my app (Delete, Save). I want the functionality such that clicking the 'Delete' button will trigger a fetch request to delete dat ...

Web application for muting and kicking users in a channel using ARI

I am currently facing a situation where two functions are triggered automatically when I add a call to a bridge. To manage this, I am trying to utilize JQuery so that these functions only execute when a specific button is clicked. This will allow me to pro ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

"Facing an issue with my handleChange function not getting triggered in MaterialUI. Can anyone

Why isn't my handleChange function being invoked with the TextField component from Material UI? Even though I can input values in the text fields, the component's state is not updating. Here is the Auth component: const Auth = () => { cons ...

Using JQuery to determine the height of a div element

I'm currently working on a full-screen fluid XHTML/CSS website. One particular challenge I have encountered involves loading content into a div element via AJAX that may exceed the visible area of the page, disrupting the full-screen layout. To addres ...

Extracting information and converting it into JSON format using Express

I am currently extracting data from a website and attempting to display it in the browser as JSON. However, although I can see the data when using console.log() on the recipes array, nothing is being sent to the browser. Why is the JSON array not showing ...

What is the most effective method for establishing a notification system?

My PHP-based CMS includes internal messaging functionality. While currently I can receive notifications for new messages upon page refresh, I am looking to implement real-time notifications similar to those on Facebook. What would be the most efficient ap ...

Retrieving the AJAX response to dynamically refresh the table with updated data

I'm a bit confused about how the server response is handled when making an AJAX request. I want to update a table by clearing it and inserting new data. The code snippet below shows how the controller responds to an AJAX request when 'triples&ap ...

How can I navigate through a highly intricate pandas JSON object structure?

My json object is quite large and follows this format: [ { "A":"value", "TIME":1551052800000, "C":35, "D":36, "E":34, "F":35, "G":33 }, { "B":"value", "TIME":1551052800000, "C":36, "D":56, "E":44, "F":75, "G":38 } ...

Varying outcomes in comparison testing

Trying to profile a function for converting a structure to an array. I have two approaches - marshaling or BitConverter. Marshaling creates a single function that can handle most structures under certain conditions, while BitConverter requires a custom fun ...

Using jQuery to read text from multiple classes within an HTML document

There are five unique div elements, each with a different id assigned. The first div appears only once, the second div repeats 1-5 times, and the remaining three divs appear more than 10 times throughout the body. I need to use jQuery to read and save the ...

Getting data from JSON using Python

Greetings! I am currently on a journey to learn Python, and one of the tasks I have at hand is to fetch the exchange rate for USD to AUD. However, I'm encountering difficulties in extracting the specific value of "AUD": 1.4817 from the JSON data that ...

How can you access the name of an array form using event.target?

I have a few checkboxes with the name checkBoxName[]. How can I retrieve the values from them? I am trying to submit them using Fetch in my handleSubmit function but encountering issues. <div> <input type='checkbox' name='ch ...

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...

Tips for designing the microphone appearance on the Google Chrome speech input interface

Google Chrome features an input control for speech recognition. If you want to know how to use it, check out this link. I'm looking to enlarge the microphone icon and possibly use a customized image for it. Increasing the width and height of the inp ...

After an Ajax request, the functionality of Javascript/Jquery ceases to work

After successfully submitting a form via ajax for the first time, the subsequent submissions seem to break all javascript functionality on the page. Additionally, the form is unable to submit with ajax again. Below is the code snippet for the ajax call: ...