How to use ScriptManager in class file?

試著忘記壹切 提交于 2019-12-04 12:53:41

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!");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!