Home

Castle Stronghold

Ajax with MonoRail: Introduction

MonoRail uses the prototype js framework to make AJAX integration easy.

Introduction

AJAX is short for "Asynchronous JavaScript and XML". It's a technique for doing background requests to the web server. Since the requests are done in the background, a full-page refresh is not required. The AJAX request can bring back a small payload -- perhaps just a small, updated section of the HTML page. Smaller payloads mean less work for the webserver and the absence of a full-page refresh gives the user a better browser experience.

Despite it's name, AJAX does not require JavaScript nor XML. At the heart of an AJAX request is simple text. However, JavaScript is often used as the scripting language to make an AJAX request and process the results.

Making an AJAX Request

Since MonoRail uses the prototype js framework, you need to make the prototype JavaScript available to your page. This can be accomplished via the AjaxHelper.

 

$AjaxHelper.InstallScripts()
          

${AjaxHelper.InstallScripts()}
          

Which will render:

<script type="text/javascript" src="/MonoRail/Files/AjaxScripts.rails"></script>
    

Let's assume we have a method on our controller called GetWeatherData. This method expects a string parameter named zipCode. When called, this method returns a snippet of HTML that represents the weather for the specific zip code.


public class WeatherDataController : SmartDispatcherController
{
  public void GetWeatherData(string zipCode)
  {
    // get weather data for zip code and place results
    // in the PropertyBag

    CancelLayout();
    RenderView("weather");
  }
}
    

The code to call this method via AJAX uses the Ajax.Request object provided by the prototype js framework.


      <script language="text/javascript">
        function UpdateWeatherData()
        {
          new Ajax.Request('$UrlHelper.For("%{action='GetWeatherData'}")',
            {
              method: 'get',
              parameters: {
                zipCode: $('zipcode').value
                },
              onSuccess: showResult,
              onFailure: showMessage
            });
        }

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

The call above uses the UrlHelper to build the URL for the AJAX call. The zipCode parameter is populated from a textfield named "zipcode". The onSuccess variable defines the function to be called on successful completion of the AJAX request. Likewise, the onFailure function will be called if there is a problem making the request.

In the example above, the response text returned from the AJAX request is used to update the weather section of the HTML page (which could be a DIV or SPAN tag).

Google
Search WWW Search castleproject.org