如何在类文件中使用ScriptManager?

时间:2011-08-05 13:02:36

标签: c# asp.net scriptmanager

我有一个使用page.clientScript显示警告消息的常用方法。但后来我添加了更新面板。现在这段代码不起作用。所以我需要在那里调用scriptmanager,但是我得到一些错误消息,它可以在那里访问。 下面是我的common.cs文件的ShowMessage方法

 private static void ShowMessage(Page currentPage, string message)
        {
            var sb = new StringBuilder();
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("');");
            currentPage.ClientScript.RegisterClientScriptBlock(typeof(Common), "showalert", sb.ToString(), true);
        }

那么如何在更新面板

下使用此方法

5 个答案:

答案 0 :(得分:4)

利用:ScriptManager.RegisterClientScriptBlock Method

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

答案 1 :(得分:3)

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

答案 2 :(得分:3)

用于类文件:

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);
        }
    }
}

这可以扩展到包括其他可能的处理程序,但目前这就是我解决问题的方法。

答案 3 :(得分:2)

在.cs文件中试试

var page = HttpContext.Current.CurrentHandler as Page;

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

这对我有用^^

答案 4 :(得分:1)

我是这样做的:

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);
    }

}

然后你就可以这样使用:

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