Using Action Return Values in Javascript
This is really basic code, and if you do improve on it, please contribute back!
Add this to your controller:
protected override void InvokeMethod(MethodInfo method, IRequest request, IDictionary actionArgs) { ParameterInfo[] parameters = method.GetParameters(); object[] methodArgs = BuildMethodArguments(parameters, request, actionArgs); object result = method.Invoke (this, methodArgs); bool isAjaxAction = method.GetCustomAttributes(typeof(AjaxActionAttribute), false).Length > 0; if(result != null) { if (isAjaxAction) { if (typeof(bool).IsAssignableFrom(result.GetType())) { RenderText( (bool)result ? Newtonsoft.Json.JavaScriptConvert.True : Newtonsoft.Json.JavaScriptConvert.False ); } else { RenderText(Newtonsoft.Json.JavaScriptConvert.SerializeObject(result)); } } else { RenderText(result.ToString()); } } }
Then create an action method which returns something:
[AjaxAction] public Post AjaxWithParams(int number, string text) { Post post = new Post(); post.Body = number.ToString(); post.Subject = text; return post; }
Now create a new Helper:
public class MyAjaxHelper : AbstractHelper { public string GetRemoteValue(string controller, string action, string callback, IDictionary parameters) { return GetRemoteValue("", controller, action, callback, parameters); } public string GetRemoteValue(string area, string controller, string action, string callback, IDictionary parameters) { string url = (area == "" ? "" : "/" + area) + "/" + controller + "/" + action + ".rails"; return "new Ajax.Request('" + url + "', { parameters:'" + BuildQueryString(parameters) + "', onSuccess: function(r) { " + callback + "(eval('(' + r.responseText + ')')); }});"; } }
DON'T FORGET: ensure you set up your controller to use this helper! Now, from some view:
<script type="text/javascript" src="/MonoRail/Files/AjaxScripts.rails"></script> <script type="text/javascript"> $MyAjaxHelper.GetRemoteValue("area", "thread", "AjaxWithParams", "callback", "%{number=5, text='howdy'}") function callback(serverObject) { alert(serverObject.Body); } </script>
You call GetRemoteValue with the area (optional), controller, action, name of a JS callback function, and Dictionary of parameters. The callback function must have one parameter, and this is the object returned from the server. In this case we'll get a Post object back and we alert the Body property on it.
