JQuery post for Action with a dictionary option

I feel deja va, but I can’t find the answer to this question: I have an array of objects that should look like this when you check the jQ $ .post call:

limiter[0].Key limiter[0].Value 

so that it appears in action

 public ActionResult SomeAction(Dictionary<Guid, string> dictionary) { } 

However, this javascript:

 // Some Guid and Some Value var param = [ { 'Key' : '00000000-0000-00000-000000', 'Value': 'someValue' } ]; $.post('/SomeController/SomeAction/', { dictionary: limiter, otherPostData: data }, function(data) { callback(data); } ) 

does this when checking it in firebug:

 limiter[0][Key] = someKey // Guid Value limiter[0][Value] = someValue 

This is in jq 1.4.2. It seems I remember some flag that you need to set up to render json differently in jQ. Is this ring ringing?

+6
source share
5 answers

Try it like this:

 var param = { '[0].Key': '28fff84a-76ad-4bf6-bc6d-aea4a30869b1', '[0].Value': 'someValue 1', '[1].Key': 'd29fdac3-5879-439d-80a8-10fe4bb97b18', '[1].Value': 'someValue 2', 'otherPostData': 'some other data' }; $.ajax({ url: '/Home/SomeAction/', type: 'POST', data: param, success: function (data) { alert(data); } }); 

The following controller action should be displayed:

 public ActionResult SomeAction(Dictionary<Guid, string> dictionary, string otherPostData) { ... } 
+3
source

You can use this flag -

 jQuery.ajaxSetting.traditional = true; 

Get jQuery to publish data in a different format with the one you see. See this question for further information -

Passing arrays when calling ajax using jQuery 1.4

+1
source

You will see post param as limiter[0][Key] , because jquery serializes json data before it places it. This is very well interpreted by the action of the controller, and you get the required input in the action.

0
source

You can also use a list of objects, and the result will be the same as you. This is a good example.

http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

0
source
 var dict = {} dict["key1"] = 1 dict["key2"] = 2 dict["key3"] = 3 $.ajax({ type: "POST", url: "/File/Import", data: dict, dataType: "json" }); public void Import(Dictionary<string, int?> dict) { } 

just send your obj as dataType: "json"

0
source

Source: https://habr.com/ru/post/894558/


All Articles