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

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Enable data insertion on a Meteor server without requiring login authentication

I am looking to develop an API that enables other apps to add new data. However, I have encountered an issue while attempting to do so. The error message "User id is required" appears because there is no logged-in user present when inserting new data. Is i ...

Gradually bringing a tag into view, gently fading it away, and then altering the text before beginning the cycle anew

I have a situation where an tag's content is being dynamically changed with jQuery and then faded in and out using the Velocity JS library along with the setInterval function. Initially, everything works smoothly for about 30 seconds. However, after ...

Adding dynamic elements to a pop-up window with the use of jQuery's .load() function

When implementing Javascript to create a modal, I have encountered an issue where the close button disappears. The modal opens and loads different HTML files dynamically using the jQuery load() method, but the close button vanishes. I suspect that the mod ...

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

Having trouble with my implementation of ConvertFrom-Json using an array in an Azure ARM template parameter - seeking help in PowerShell

I'm attempting to include a $paramObject in a fresh ARM template deployment. I suspect that there is something missing in my PowerShell script to properly convert the arrays for template usage. $ResourceGroupName = "rg-testtemplate" New-AzRes ...

Imitate a style using jQuery without deleting other elements

This is an example of HTML code: <div id="id1" style="width:100px;background: rgb(196, 14, 14);">1</div> <div id="id2" style="margin-top:10px">2</div> to <div id="id1" style=&qu ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one? For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are anot ...

Change the Bootstrap components according to the size of the screen

Is there a built-in Bootstrap feature to change an element's class based on screen size? I'm working on a webpage with scrollable card elements. On desktop, the cards are arranged horizontally, but on mobile they are stacked vertically, requirin ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

The Heroku app is down because it can't find the module named 'hjson'

Recently, I integrated hjson into my Python application and hosted it on a Heroku server. However, upon pushing the updated code with hjson imports, my app crashed. Upon running heroku logs --tail, here is the stack trace: import config, requests, hjson 2 ...

not capable of outputting findings in a sequential manner

I am encountering an issue where my result is not printing line by line, instead everything shows up on a single line. How can I resolve this problem? Here is the code snippet I have tried: <script> function know(){ var num = Number(doc ...

Inform jQuery that the draggable element is in the process of being dragged dynamically

Currently, this issue is a vital component of an ongoing task. Once we can resolve this issue, it will lead to the completion of this and another inquiry. The original objective can be found here: drag marker outside map to html element You can view the ...

Changing the li tag by clicking on it is a simple task that can be easily

Whenever I click on a tag, I want the li class to change to "active" and open a new page with the corresponding tag as active. For example, if I click on the Overview tag, the new page should open with the li tag as active. I have attempted to write some c ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

Display error messages upon submitting the form

I am currently working on an Angular 6 Form with validation. My main goal is to display error messages only after the form has been submitted. It is crucial that these messages remain constant while the user types in the input field. For instance, if a use ...

How can you execute PHP code within another PHP script without triggering a redirect?

I'm faced with a situation where I have two php files, namely abc.php and def.php. My goal is to only display abc.php in the browser URL bar when it executes. Additionally, upon clicking the submit button on my HTML page, abc.php should be triggered t ...