mvc controllers and json objects

Last post 07-03-2009 4:37 PM by crpietschmann. 3 replies.

Sort Posts:

  • mvc controllers and json objects

    12-16-2007, 7:06 PM
    • Member
      2 point Member
    • DragonFist
    • Member since 12-16-2007, 11:59 PM
    • Posts 7

    the mvc views seem capable of sending json as I have used them for this.  However, I have several attempts to pass json objects as parameters to a controller action without success.

     

    Is JSON simply not supported in this release?

    Best,

     Shawn

  • Re: mvc controllers and json objects

    12-17-2007, 7:10 AM
    Answer

    Hi there

    It's pretty easy to handing incoming JSON data in an action method, by using either JavaScriptSerializer or the slightly more awkward DataContractJsonSerializer. For example:

    [ControllerAction]
    public void ProcessJSON(string customerJsonData)
    {
    // Get a deserializer
    System.Web.Script.Serialization.JavaScriptSerializer serializer =
    new System.Web.Script.Serialization.JavaScriptSerializer();

    // You could deserialize to a name-value pair, and access it as a weakly-typed object
    IDictionary<string, object> myObject =
    serializer.Deserialize<IDictionary<string, object>>(customerJsonData);
    ViewData["name"] = myObject["Name"];

    // Or, ideally, deserialize to a strongly-typed object
    Customer myCustomer = serializer.Deserialize<Customer>(customerJsonData);
    ViewData["name"] = myCustomer.Name;

    RenderView("CustomerDetails");
    }
    If you are trying to receive the JSON data as a strongly-typed .NET object directly on your parameter list (e.g. changing the method signature above to ProcessJSON(Customer customerJsonData)), then no, unfortunately that won't work, you have to deserialize manually. If you're familiar with MonoRail's JsonBinder, you might like to check out hammet's experiment to add MonoRail-style parameter binding to ASP.NET MVC.
  • Re: mvc controllers and json objects

    12-18-2007, 10:47 PM
    • Member
      2 point Member
    • DragonFist
    • Member since 12-16-2007, 11:59 PM
    • Posts 7

    I have no problem serializing the json manually.  I was having trouble having the json string pass at all.  Small strings were no problem but a json string wasn't passing to a parameter cast as either an object or string.

  • Re: mvc controllers and json objects

    07-03-2009, 4:37 PM
    • Participant
      917 point Participant
    • crpietschmann
    • Member since 07-05-2002, 5:06 PM
    • Wisconsin, USA
    • Posts 221

    I know this is an old post, but I just figured out how to do this using a custom ModelBinder, so I thought I'd share the link to my solution here.

    http://stackoverflow.com/questions/1077481/how-do-i-pass-a-dictionary-as-a-parameter-to-an-actionresult-method-from-jquery-a

    Microsoft MVP - Windows Live Platform
    Blog: http://pietschsoft.com | Web.Maps.VE - ASP.NET AJAX Bing Maps Control
Page 1 of 1 (4 items)