简体   繁体   中英

How to pass json as object to ASP.NET MVC controller?

I have an action

[HttpGet]
public ActionResult Index(MyObject obj)
{
   return View(obj);
}

and an object:

 [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
 public class MyObject
 {
    [JsonProperty(PropertyName = "someString")]
    public String SomeString
    {
        get { return _someString; }
        set { _someString = value; }
    }

    [JsonProperty(PropertyName = "someDictionary")]
    public IDictionary SomeDictionary
    {
        get { return _someDictionary; }
        set { _someDictionary = value; }
    }

    public MyObject()
    {
    }

    private String _someString;
    private IDictionary _someDictionary;
  }

I want to pass this object to action by url. So I create url:

String url =  controller.Url.Action("Index", "SomeController");
url += "?obj=" + JsonConvert.SerializeObject(myObjectInstance);

It's create me an url with json, but when I use it - the object in url is null.

Can anybody help me?

Thanks!

UPDATED: Share instance of my MyObject as reaction to comments:

MyObject myObjectInstance = new MyObject ();
myObjectInstance.SomeString = "Hello";
myObjectInstance.SomeDictionary = new Dictionary<String, Object> 
{
   {"firstKey","value"}, 
   {"secondValue",5}
}

The modelbinder is capable of deserializing JSON. In other words, you don't need to do anything special. If you're request body consists of JSON (not a JSON string mind you, but an actual JSON object with a JSON mimetype), then as long as it can bind the data to the action parameter, it will. In other words, all you need to do is contruct one or more C# classes to represent the JSON object. For example, given a JSON object like:

{
    'foo': 'bar',
    'bar': 1
}

You'd need a class like:

public class MyClass
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}

Then, this goes into your action signature:

public ActionResult MyAction(MyClass foo)

The modelbinder will new up an instance of MyClass and bind the JSON data onto the relevant properties.

Other than the fact that you should never engage in such atrocious behavior (you should only pass the object's ID in the link)... technically, you could do it this way:

public ActionResult Index(string myObjectJson)
{
     var myObject = Json.Deserialize<MyObject>(myObjectJson);

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