2

I don't understand why in my controller's action I get null as string:

Here is ajax call:

var dict = { "A": "fake1", "B": "fake2" };
var data = { "dictionary": JSON.stringify(dict) };

$.ajax({
    url: '/MyController/MyMethod',
    data: JSON.stringify(data),
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json'
});

And action method:

[HttpPost]
public ActionResult MyMethod( string dictionary )
{
    Dictionary<string, string> usersToNotify = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>( dictionary );
    //...
}
13
  • Not sure about asp, but you may need parenthesis around the new JavaScriptSerializer() before trying to access from it Commented Dec 14, 2015 at 10:27
  • I wouldn't stringify dict in the data object. Just add dict to data and then stringify the whole lot. Commented Dec 14, 2015 at 10:29
  • Why not just have a model with string A and string B and post back to the model? - data: { "A": "fake1", "B": "fake2" } and delete the contentType option Commented Dec 14, 2015 at 10:30
  • Possible duplicate of POST json dictionary Commented Dec 14, 2015 at 10:33
  • Could you just test to change in the ajax call the data: JSON.stringify(data), to data: data, because you don´t need to stringify the param object name Commented Dec 14, 2015 at 10:33

1 Answer 1

0

Have you tried this?

   var dict = { "A": "fake1", "B": "fake2" };
   var data = { "dictionary": JSON.stringify(dict) };

   $.ajax({
   url: '/MyController/MyMethod',
       data: {
        dictionary:data.dictionary
       },
       type: 'POST',
       contentType: 'application/json',
       dataType: 'json'
   });
Sign up to request clarification or add additional context in comments.

3 Comments

dictionary:JSON.stringify(dict) instead of dictionary:data.dictionary
With this it doesn't find my methdod, doesn't come into it.
Do you mean that the request is not sent of what?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.