SharePoint: Invoke server side code on SharePoint ribbon click using javascript _dopostback and delegate control

Scenario: Invoke server side code on SharePoint ribbon click using javascript _dopostback and delegate control

In this series we will look at three different ways of achieving this.
2. Invoke server side code on SharePoint ribbon click using javascript _dopostback

Create a SharePoint 2010 Empty solution and add two empty element files to it. One to specify the delegate control and other to specify the Custom Action. Also add a Layouts folder and add a javascript file to it. Lastly add a Control Templates mapped folder and add a user control to it.
Add the following in the elements file of delegate control.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="">
       <Control Id="AdditionalPageHead"
           ControlSrc="~/_CONTROLTEMPLATES/DemoDelegate.ascx" />

Add following code to Custom Action element file:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="">
                                   Alt="Ribbon Demo"
                                   LabelText="Ribbon Demo"
                                   ToolTipTitle="Ribbon Demo"
                                   ToolTipDescription="Ribbon Demo example."/>
       <CustomAction Id="RibbonDemo.Scripts"
                             ScriptSrc="/_Layouts/SharePointRibbonDemo/RibbonDemoScript.js" />

Add the following code in the javascript file:
function RibbonDemo() {
    var context = SP.ClientContext.get_current();
    var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
    var listId = SP.ListOperation.Selection.getSelectedList();
    var itemIds = "";
    for (var i = 0; i < selectedItems.length; i++) {
        itemIds += selectedItems[i].id + ",";
    __doPostBack('RibbonDemo', itemIds + ";" + listId);    
    context.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Failed));

function Success() {
var theForm = document.forms[0];
        theForm.__EVENTTARGET.value = "";
        theForm.__EVENTARGUMENT.value = "";

function Failed(sender, args) {
    alert('request failed ' + args.get_message() + 'n' + args.get_stackTrace());

function RibbonDemoEnable() {   
    var context = SP.ClientContext.get_current();
    return SP.ListOperation.Selection.getSelectedItems(context).length >= 1;

Write the following code in the code behind file of the delegate control on Page Load or CreateChildControls method:

if (this.Page.Request["__EVENTTARGET"] == "RibbonDemo")
                string parameter = this.Page.Request["__EVENTARGUMENT"];
                int index = parameter.IndexOf(';');
                string listID = parameter.Substring(index + 1);
                string itemIds = parameter.Substring(0, index);
                string[] itemIdArray = itemIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                // Further code implementation