Geeks With Blogs

AzamSharp Some day I will know everything. I hope that day never comes.

In my previous post I talked about that by using AJAX.NEt Library I am not able to access the JavaScript methods which were to be called from the Page. One solution is to Inject the JavaScript into the page which is using AJAX. Take a look at the code below:

This is the code for the BasePage:

public class BasePage : System.Web.UI.Page
    {
        
private const string SCRIPT = "ScriptString"; 
        

        [Ajax.AjaxMethod] 
        
public string GreetUser() 
        {
            
return "Hello World";
        }

        
public void InjectScript() 
        {
            
string scriptString = String.Empty; 

            
if(Cache[SCRIPT] == null
            {
                scriptString = GetScript(); 
                Cache[SCRIPT] = scriptString; 
            }
            
            
else 
            
{
                scriptString =(
string) Cache[SCRIPT]; 
            }
            
            
if(!Page.IsClientScriptBlockRegistered("script")) 
                Page.RegisterClientScriptBlock("script",scriptString); 
 
        }

        
private string GetScript() 
        {
            
string script = String.Empty; 

            FileStream fs = File.OpenRead(Server.MapPath("AjaxScript.js")); 
            StreamReader sr = 
new StreamReader(fs); 
            
while(sr.Read() > -1) 
            { 
                script = sr.ReadToEnd(); 
            }
            
            fs.Close(); 
            sr.Close(); 

            
if(script != null && script.Length > 0) 
                
return script; 
            
else return null

        }

And the page that wants to use the AJAX functionality can simply inherit from the BasePage and fire the InjectScript method which will inject the JavaScript into the page. 

WebForm1.aspx code: 

public class WebForm1 : BasePage

{

private void Page_Load(object sender, System.EventArgs e)

{

Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1));

InjectScript();

}


 

powered by IMHO 1.3

Posted on Wednesday, February 15, 2006 2:16 PM | Back to top


Comments on this post: Injecting the Script

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net