C#脚本块寄存器

时间:2015-09-02 10:44:16

标签: c# asp.net webforms

任何人都可以帮助我,因为我试图首先注册一个脚本并绑定一个名为" DoClick()"的函数。使用C#进入按钮但在运行时发生了一些错误。请看下面的代码。这样当按钮被点击时,他们会调用函数" DoClick()。谢谢大家

public void regiterAdsScript(int loc)
{
    string adsLink = ads_link(loc);       
    // Define the name and type of the client script on the page.
    String csName = "ButtonClickScript";
    Type csType = this.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;
    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(csType, csName))
    {
        StringBuilder csText = new StringBuilder();
        csText.Append("<script type=\"text/javascript\"> \n");
        csText.Append("function DoClick() { <script type='text/javascript' src='//abcd.site?id=123'></script> }  \n");
        csText.Append("</script>");
        cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
        Button1.Attributes.Add("onClick", "return DoClick()");

    }
}

1 个答案:

答案 0 :(得分:1)

您的脚本注册码应该是这样的

Button1.Attributes.Add("onClick", "javascript:DoClick();");

此外,您的脚本看起来不对。无论您希望脚本执行什么操作,都应该遵循函数声明。就像你想要发出警报一样,它应该是这样的

csText.Append("function DoClick() { alert('MK'); }  \n");

在调用Button1_Click之前,还需要调用函数 regiterAdsScript()。我在Page_load本身中调用了它。以下是您的示例程序:

protected void Page_Load(object sender, EventArgs e)
{
    regiterAdsScript();  
}
protected void Button1_Click(object sender, EventArgs e)
{
    //functionality to be implemented
}
public void regiterAdsScript()
{
    string adsLink = ads_link(loc);
    // Define the name and type of the client script on the page.
    String csName = "ButtonClickScript";
    Type csType = this.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;
    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(csType, csName))
    {
        StringBuilder csText = new StringBuilder();
        csText.Append("<script type=\"text/javascript\"> \n");
        csText.Append("function DoClick() { alert('MK'); }  \n");
        csText.Append("</script>");
        cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
        Button1.Attributes.Add("onClick", "javascript:DoClick();");
    }
}