Home

Castle Stronghold

Javascript Action Proxies

MonoRail includes the ability to generate a proxy object in javascript to invoke actions on controllers. For example, suppose you have the following controller:


using Castle.MonoRail.Framework;

public class AdminController : SmartDispatcherController
{
    public void Index()
    {
    }

    [AjaxAction]
    public void DisableUser(int userId)
    {
        // Do something important here
        RenderText("Done");
    }

    [AjaxAction]
    public void ChangeUserPassword(int userId, String newPassword)
    {
        // Do something important here
        RenderText("Done");
    }
}

The methods you want to generate proxies for need to be marked with the attribute AjaxActionAttribute.

On the view side, you can use the following methods to generate a javascript block that uses AjaxRequest class to invoke the actions.

In the view for the Index action of AdminController we can generate a proxy:

 

$AjaxHelper.InstallScripts()
$AjaxHelper.GenerateJSProxy("myproxy")

The GenerateJSProxy call will generate a js block that uses Ajax.Request to make a remote invocation:


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

    DisableUser:
    function(userId, callback)
    {
        var r=new Ajax.Request('/admin/DisableUser.rails',
        {
            parameters: '_=x26userid=' + userId,
            asynchronous: !!callback,
            onComplete: callback
        });
        if(!callback) return r.transport.responseText;
    }
,
    ChangeUserPassword:
    function(userId, newPassword, callback)
    {
        var r=new Ajax.Request('/admin/ChangeUserPassword.rails',
        {
            parameters: '_=&userId=' + userId + '&newPassword=' + newPassword,
            asynchronous: !!callback,
            onComplete: callback
        });
        if(!callback) return r.transport.responseText;
    }
}
</script>

As you see it supports synchronous and asynchronous calls. If you specify a callback function it will be asynch, otherwise synchronous. The use of the remote method becomes natural js code:


<input type="button" onclick="javascript:myproxy.DisableUser($('userid'));" />

You may also consult the API documentation for the AjaxHelper.

Google
Search WWW Search castleproject.org