Simple way for making POST request with silverlight

I came up with this way to make a post request from silverlight because I find the WebClient too cumbersome and the post requests to relative URLs didn't work. My solution is to use javascript for making the posts with Ajax and then call the javascript method from the silverlight. First we have the javascript on the page for making the post with jQuery:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.4");
function makeRequest(url, args) {
    $.ajax({type: 'POST', url: url, data: args});
}
</script>
Thanks to jQuery the code is really short. Then we have the helper class for making the post request from silverlight, here the trick is the ToJSDictionary-method converting the arguments dictionary to a javascript object.
public class WebHelper {  
    public static void MakeRequest(string url, 
            IDictionary<string, object> args) {
        try
        {
            HtmlPage.Window.Invoke("makeRequest",url, 
                    ToJSDictionary(args));
        }
        catch (Exception e)
        {
            // Ignored  
        }
    }

    public static object ToJSDictionary(IDictionary<string, object> args)
    {
        var jsdict = HtmlPage.Window.CreateInstance("Object");
        foreach (string key in args.Keys)
        {
            jsdict.SetProperty(key, args[key].ToString());
        }
        return jsdict;
    }
}
Now we can make post requests from our silverlight code like this:
    var args = new Dictionary<string,object>();
    args["p1"] = "test";
    args["p2"] = 1;
    WebHelper.MakeRequest("http://my.site.com/test", args); 
Of course since we are not handling the response this approach is only suitable when that is not required.

No comments:

Post a Comment