开发者

send JavaScript object with unknown properties to asp.net MVC controller

I have read quite some blogs and stackoverflow answers on how to send a JavaScript object to an asp.net MVC controller. But all examples I have seen so far require you to know which properties the JavaScript object will have (because they all convert the JavaScript object to a C# object).

When I was using PageMethods in asp.net webforms I could send any complex JavaScript object or array (even hierarchical data) and it would be converted to a Dictionary which I could iterate. Any chanc开发者_运维技巧e I can do something similar in asp.net MVC?


I now found a way which works for me.

  1. I am converting my data to json and receive it as a string in my ASP.net MVC controller.
  2. Then I use the json.net library to read the data - since this library allows me to read the data without converting it to a C# (or VB) object.

JavaScript code:

//first include the json2 library for older browsers and jQuery
$.post(url, {json: JSON.stringify(mydata)});

Server side code:

public void xyz(string json)
{
    JObject j = JObject.Parse(json);
    string name = (string)j.SelectToken("Products[0].Name");
    //...
}

The good thing: it is "normal" json which means it is not some uncommon format or interface-type.

EDIT: I found out that I don't even need the C# json-library if I am using .net 4 - since I can convert any json string to a Dictionary with the help of the JavaScriptSerializer:

JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> data = (Dictionary<string, object>) jss.Deserialize<dynamic>(json_string);


What you can do is use jQuery plugin toDictionary, this plugin will transform your object to dictionary that asp.net MVC default model binder can understand

e.g.

 $.ajax({
    url: "/SomeURL",
    type: "POST",
    data: $.toDictionary(dataToSend)
   });

Remember dataToSend is your object


This will be converted to a dictionary:

[{"key":0, "value":"something"},{"key":2, "value":"something else"},]

Obviously, you could do string,string or int, bool or etc...

For example, I have a method like this:

public int CollabSortFolder(int FolderId, Dictionary<int, int> Items)

I would call is using a GET:

/CollabSortFolder?FolderId=111111&Items=[{"Key":3685,"Value":0},{"Key":3670,"Value":1},{"Key":3687,"Value":2}]

Now as a GET it's not very elegant, but a post would work the same way.


Have you tried using the Request.Forms dictionary?

public ActionResult MyAction(FormCollection formValues)
{
}

Iterate over formValues

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜