添加javascript来控制的问题

时间:2011-05-04 13:39:36

标签: c# javascript

我在.cs页面中使用此脚本..

public void messagebox(string msg)
{
  Label lbl = new Label();
  lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
  Page.Controls.Add(lbl);
}

错误

无法修改Controls集合,因为该控件包含代码块(即&lt;%...%&gt;)。

3 个答案:

答案 0 :(得分:2)

要注册脚本,请使用ScriptManager

ScriptManager.RegisterStartupScript(this, this.GetType(), "registeredAlert", lbl, false);

答案 1 :(得分:1)

要在页面上注册脚本,请使用RegisterStartupScript

ScriptManager.RegisterStartupScript Method (Control, Type, String, String, Boolean)

如果您使用的是更新面板,则必须使用updatepanel控件调用前两个参数

ScriptManager.RegisterStartupScript(updatePanel,
    updatePanel.GetType(),
    "key",            // unique key means it will never insert the same script twice
    "alert('hi');",   // javascript
    true);            // include <script> tags

答案 2 :(得分:0)

这与Javascript无关。错误信息非常清楚;您不允许在代码中的此处向Page.Controls添加任何其他控件。