开发者

problem adding javascript to control

开发者 https://www.devze.com 2023-03-02 23:51 出处:网络
i am using this script in.cs page.. public void messagebox(string msg) { Label lbl = new Label(); lbl.Text = \"<script language=\'javascript\'>\" + Environment.NewLine + \"window.alert(\'\" + m

i am using this script in .cs page..

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

error as

The Controls collection cannot be modi开发者_JAVA百科fied because the control contains code blocks (i.e. <% ... %>).


To register a script, use ScriptManager

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


To register a script on the page use RegisterStartupScript

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

If you are using an update panel you have to call the first two parameters with the updatepanel control

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


This has nothing to do with Javascript. The error message is pretty clear; you're not allowed to add any more controls to Page.Controls at that point in your code.

0

精彩评论

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