Home

Castle Stronghold

JSON

MonoRail has built-in support for both sending and receiving JSON objects.

Introduction to JSON

JSON stands for "Javascript Object Notation". It's a lightweight interchange format used to represent simple JavaScript objects as text. MonoRail supports both receiving a JSON object in an AJAX request as well as returning a JSON object to an AJAX request.

Receiving a JSON object

While MonoRail's DataBinder is used to populate objects from data found inside the HTTP request, the JSONBinder is used to populate objects from JSON data found inside the HTTP request.

Let's assume we have a simple JavaScript class that contains some data:


      <script language="text/javascript">
        function UserData(name, age)
        {
          this.Name = name;
          this.Age = age;
        }
      </script>    
    

We can use the AjaxRequest object to send an entire instance of the UserData class to a controller method in our .NET code.

Quick Note

Remember when using the AJAX features to install the prototype js library by using $AjaxHelper.InstallScripts().


    // NOTE: Use VS2008 property syntax
    public class UserData
    {
      public string Name { get; set; }
      public int Age { get; set; }
    }

    public void UserController : SmartDispatcherController
    {
      public void GetUpdatedUserData([JSONBinder("ud")]UserData data)
      {
        // use "data" as any other C# object
      }
    }
    

In the code above, we first have a C# class that has the same definition as our JavaScript class. With the JSONBinder attribute, we tell MonoRail that an HTTP request coming to GetUpdatedUserData containing a data element called "ud" should be mapped via JSON to an instance of the UserData class. Here's some sample code that would send the "ud" data to GetUpdatedUserData.


      <script language="text/javascript">
        function UpdateUserData()
        {
          var userdata = new UserData('Patrick Steele', 41);
          new Ajax.Request('$UrlHelper.For("%{action='GetUpdatedUserData'}")',
            {
              method: 'get',
              parameters: {
                ud: Object.toJSON(userdata)
                },
              onSuccess: showResult,
              onFailure: showMessage
            });
        }

        function showResult(transport)
        {
          $('userinfo').innerHTML = transport.responseText;
        }
        
        function showMessage(transport)
        {
          alert('An error occurred during the AJAX request.');
        }
      </script>
    

The code above creates a UserData object in JavaScript. It then makes an AJAX request to GetUpdatedUserData and passes the JSON version of the UserData to the controller.

Sending a JSON object

Sending the JSON version of a C# class or struct is accomplished in a similar fashion to receiving a JSON object.

Here's some C# code that returns an instance of the UserData class defined above.


        [return:JSONReturnBinder]
        public UserData GetData()
        {
      UserData fromCsharp = new UserData();
      fromCsharp.Age = 32;
      fromCsharp.Name = "Bob Smith";

      return fromCsharp
        }
    

The JSONReturnBinder attribute instructs MonoRail to serialize the resulting return value as a JSON object. The prototype framework has a built-in method for recreating the JSON object in the browser:

Quick Note

In the interest of brevity, only the AJAX onSuccess handler is show below.


      <script language="text/javascript">
        function showResult(transport)
        {
          var newData = transport.responseText.evalJSON();
        }
      </script>
    
Google
Search WWW Search castleproject.org