简体   繁体   中英

How to send a JSON stringified javaScript object to the server

I'm using VB.Net and MVC 5. I have a an object I am creating with javaScript like this:

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

I need to send this object to my controller and move on to the next view with the information it contains.

I can successfully stringify the object and pass it to the controller via ajax, and manipulate the data, but this does not allow me to render the new view on success.

I tried to use window.location and endodeURIComponent like this:

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

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

            window.location = postString;

But I receive this error still:

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

Which I find odd, because I cannot see any :'s in the request:

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

What is the proper way to pass this object via javaScript or jQuery to the controller, and have the server render the new view?

It is getting URL encoded because you're using an HTTP GET. If you're sending lots of info like this, you likely want to be using an HTTP POST. See jQuery's $.ajax method.

If you really wanted to continue using a GET rest assured that if your action took in a string parameter, it will come through as expected with the colons. The : is getting encoded to %3A (see: http://www.w3schools.com/tags/ref_urlencode.asp for all of them).

I solved this issue by placing my JSON string into a session variable with an AJAX call and then calling the action for the proper view on success using window.location . I then retrieve the string from the session when the 'success' action is called to set up my model for the view.

probably the dangerous request issue showed up because of trying to inject url path '/ViewDetails/EditConfirmation/' + myEdits into the browser.

Model Class

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

Javascript Part(assuming jQuery) - sending yor myEdits object

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

HomeController

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM