Sending a JSON stringified JavaScript object to a server: A step-by-step guide

I am currently working with VB.Net and MVC 5. In my project, I have an object that I created using javaScript:

        var myEdits = {
            listOfIDs: [],
            listOfValues : []
        };

My goal is to send this object to the controller and proceed to the next view with all the relevant information.

While I am able to successfully stringify the object and send it to the controller using ajax, I face a challenge in rendering the new view upon success.

I attempted to use window.location along with encodeURIComponent as follows:

            myEdits = encodeURIComponent(JSON.stringify(myEdits));

            var postString = ("/ViewDetails/EditConfirmation/" + myEdits);

            window.location = postString;

However, I still encounter this error:

A potentially dangerous Request.Path value was detected from the client (:).

This error confuses me as I do not see any colons in the request path:

EditConfirmation/%7B"listOfIDs"%3A%5B"22"%2C"23"%2C"24"%2C"25"%2C"26"%2C"27"%2C"28"%2C"29"%2C"30"%2C"31"%2C"32"%2C"33"%2C"34"%2C"35"%2C"36"%5D%2C"listOfValues"%3A%5B""%2C""%2C""%2C""%2C""%2C""%2C""%2C""%2C""%2C""%2C"Yes"%2C"Yes"%2C"Yes"%2C"Yes"%2C"No"%5D%7D

Can someone advise on the correct method of passing this object via javaScript or jQuery to the controller and ensuring that the server renders the new view?

Answer №1

When using an HTTP GET, URLs are automatically encoded. To avoid this and properly send large amounts of data, consider switching to an HTTP POST method. Utilize jQuery's $.ajax function for assistance.

If you prefer to stick with a GET request, be aware that if your endpoint expects a string parameter containing colons, they will still be preserved in the encoded format (e.g., : becomes %3A). Visit http://www.example.com/urlencodeguide for a comprehensive list of encoded characters.

Answer №2

To resolve the problem, I stored my JSON string in a session variable using an AJAX request and triggered the appropriate view action on success by utilizing window.location. Later on, I fetched the string from the session during the 'success' action execution to prepare my model for display.

Answer №3

It seems that the issue with the unsafe request occurred when attempting to inject the URL path

'/ViewDetails/EditConfirmation/' + myEdits
into the browser.

Model Class Definition:

public class myEdits
{
    public List<int> listOfIds {get;set;}
    public List<string> listOfValues {get;set;}
}

Javascript Section (assuming jQuery) - sending your myEdits object:

$.ajax({
  type: "POST",
  url: 'Home/MyMethod',
  data: myEdits,
  success: success,
  dataType: dataType
});

HomeController Method:

public void MyMethod(myEdits edits)
{
    return View("/ViewDetails/EditConfirmation/", edits);
}

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

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

Having difficulty linking a click event to an Anchor tag within a React component

Here is the code snippet for ComponentA.js: This is the return statement inside the component return ( ...... <a id="MytoolTip" ...... <ComponentB content={ ` <div class="share_cart_tt ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Learn how to effectively share an image using the Math.random function

Is there a way to display a random number of images on a webpage using JavaScript? Let's say we want to show X number of images, where X is a randomly generated number. For the sake of this example, let's set X to be 10. <input class="randomb ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Extracting data from a JSON format in Flask is a crucial task that can be

Can someone please help me with extracting data from JSON format? I am trying to create a search input in JSON and then retrieve information from MYSQLdb. Here is the data I have: {"result":[[21,"bogdan333","bogdan333",0,"","templates/UPLOAD_FOLDERp7.jpg" ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Enabling communication between App.js and a separate class in React

How can I integrate React Scheduler with JSON data in my app and pass shifts and functions from App.js to DataSheet.js for updating the data? Is there a more efficient way to enable database updates directly from DataSheet? App.js: import React from &apos ...

What is the simplest method for invoking a C# function from JavaScript?

I am facing an issue with a LinkButton control in my project. I need to attach a c# method to it, but when I add the control to the page using parse control function, it changes the call to javascript and results in an undefined error. I have been trying t ...

Is it practical to extract the page type/name from the CSS of the selected tab?

My website has multiple tabs on a single page and I want to integrate Google Analytics code. However, since all the tabs are part of the same page, I need a way to track which tab the user is interacting with. Would using CSS to check for the selected tab ...

I created a customized version of jQuery tabs, but I am looking for an external link to display the tab content and to style the original navigation

I've been experimenting with modifying a tabs script in jQuery that I came across. It seems like my attempt to enhance it has made things more complex than necessary. While I know creating tabs with jQuery is simple, I wanted to create my own version ...

"Is there a way to adjust the range slider to display currency instead of

I stumbled upon this amazing slider on codepen. Can someone guide me on how to adjust it to display a range from €500 to €6000 while keeping the vibrant red background? I've attempted various solutions like: <input id = "range" type = "range ...

Verify if the text field is currently blank or has content before applying attributes

How can I disable one text box if another specific text box is filled within a div containing multiple text boxes? For example: When I enter text in textbox(4), I want to automatically disable textbox(1). And if I remove the text from textbox(4), I want t ...

Illustrating SVG links

I'm working on a basic svg animation project where I want to create a simple shape by animating a line under a menu link. The goal is to have a single line consisting of a total of 7 anchors, with the middle 3 anchors (each offset by 2) moving a few p ...