开发者

How to use ScriptManager in class file?

I Have a common method that displays alert message using page.clientScript. But later on i added update panel. Now this piece of code is not working. So I need to call there scriptmanager, but i get some error message that it is accessible there. Below is my ShowMessage method of common.cs file

 private static void ShowMessage(Page currentPage, string message)
        {
            var sb = new StringBuilder();
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("');");
            currentPage.ClientScript.Reg开发者_运维技巧isterClientScriptBlock(typeof(Common), "showalert", sb.ToString(), true);
        }

So how do I use this method under update panel


Make use of : ScriptManager.RegisterClientScriptBlock Method

ScriptManager.RegisterClientScriptBlock(
            this,
            typeof(Page),
            "TScript",
            script,
            true);


const string scriptString = "<script type='text/javascript'> alert('message');</script>";
                ClientScriptManager script = Page.ClientScript;
                script.RegisterClientScriptBlock(GetType(), "randomName", scriptString);


For use in a class file:

public static void SendAlert(string sMessage)
{
    sMessage = "alert('" + sMessage.Replace("'", @"\'").Replace("\n", @"\n") + "');";

    if (HttpContext.Current.CurrentHandler is Page)
    {
        Page p = (Page)HttpContext.Current.CurrentHandler;

        if (ScriptManager.GetCurrent(p) != null)
        {
            ScriptManager.RegisterStartupScript(p, typeof(Page), "Message", sMessage, true);
        }
        else
        {
            p.ClientScript.RegisterStartupScript(typeof(Page), "Message", sMessage, true);
        }
    }
}

This could be expanded to include other possible handlers, but for the moment this is how I solved the problem.


Try this in .cs file

var page = HttpContext.Current.CurrentHandler as Page;

ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('Success');window.location ='Home.aspx';", true);

It's working for me ^^


Here's how I did it:

public partial class JQuery
{

    private Page page;      
    public JQuery(Page pagina) {
        page = pagina;
    }

    public void Alert(string Title, string Message)
    {

        Message = Message.Replace("\n", "<br>");

        string command = String.Format("myCustomDialog('{0}','{1}')", Title, Message);
        ScriptManager.RegisterClientScriptBlock(page, this.GetType(), "", command, true);
    }

}

Then you can use like this:

JQuery jquery = new JQuery(this.Page);
jQuery.Alert("Title", "Look, a jQuery dialog!");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜