How to build C# object from a FormCollection with complex keys

放肆的年华 提交于 2019-12-07 22:23:44

问题


i have a javascript object, obj, that gets passed to an mvc action via a $.post() like so:

var obj = {
    Items: [{ Text: "", Value: { Property1: "", Property2: "" },
            { Text: "", Value: { Property1: "", Property2: "" }]
};
$.post('MyAction', obj, function() {});

the action signature looks like this:

public ActionResult MyAction(FormCollection collection)
{
}

i need to be able to build an object from the FormCollection, however i'm running into an issue where the keys are in the form:

"Items[0][Text]"
"Items[0][Value][Property1]"
"Items[0][Value][Property2]"
"Items[1][Text]"
"Items[1][Value][Property1]"
"Items[1][Value][Property2]"

i'm wondering if there's a clean way to build the desired C# object from the given FormCollection. i understand that i could change the action method signature to take in the type of object i'm interested in, but that was presenting its own issues.


回答1:


If you can change the javascript side so you're sending in a json version of the data instead, I would think you could either accept a string and do a json deserialization yourself in the controller or do a model binder to do it for you.

  • http://code.google.com/p/jquery-json/
  • ASP.Net MVC : Sending JSON to Controller
  • http://api.jquery.com/serializeArray/


来源:https://stackoverflow.com/questions/2845304/how-to-build-c-sharp-object-from-a-formcollection-with-complex-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!