using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Telerik.Web.UI;
using System.IO;
using System.Web.UI.HtmlControls;

public partial class Default18 : System.Web.UI.Page
{ 
    const string BeginRenderControlBlockMarker = "<!-- BEGIN RENDERCONTROL BLOCK -->";
    const string EndRenderControlBlockMarker = "<!-- End RENDERCONTROL BLOCK -->";

    [WebMethod]
    public static Dictionary<string,string> GetGrid()
    {        
        StringWriter tw = new StringWriter();
        Control control = null;
        Page page = new Page();
        page.EnableViewState = false;
        control = page.LoadControl("~/TemplateUserControl.ascx");
        HtmlForm form = new HtmlForm();
        form.ID = "__form";
        page.Controls.Add(form);
        ScriptManager scriptManager = new ScriptManager();
        scriptManager.ID = "Manager";
        form.Controls.Add(scriptManager);
        form.Controls.Add(new LiteralControl(BeginRenderControlBlockMarker));
        form.Controls.Add(control);
        form.Controls.Add(new LiteralControl(EndRenderControlBlockMarker));

        HttpContext.Current.Server.Execute(page, tw, true);

        string markup = tw.ToString();
        string htmlToServe = StripControl(markup);        

        Dictionary<string, string> data = new Dictionary<string, string>();
        data["markup"] = htmlToServe;
        data["script"] = StripScript((IScriptControl)control.FindControl("RadGrid1"));
        return data;        
    }

    protected static string StripScript(IScriptControl control)
    {
        IScriptDescriptor descriptor = (IScriptDescriptor)(control.GetScriptDescriptors() as List<ScriptDescriptor>)[0];        
        return descriptor.GetType().GetProperty("Script").GetValue(descriptor, null).ToString();                 
    }

    protected static string StripControl(string markup)
    {
        int startIndex = markup.IndexOf(BeginRenderControlBlockMarker) + BeginRenderControlBlockMarker.Length;
        markup = markup.Substring(startIndex);
        int endIndex = markup.IndexOf(EndRenderControlBlockMarker);
        markup = markup.Substring(0, endIndex);
        return markup;
    }
}
