ASP.NET C#使用ClientScript.RegisterStartupScript传递参数

本文关键字:参数 RegisterStartupScript ClientScript NET 使用 ASP | 更新日期: 2023-09-27 18:22:34

我有下面的代码,它应该在我的客户端脚本中调用一个名为ShowPopup的函数,但出于某种原因,当我调用这个函数时,什么都不会发生。

  string pg = "Test";
  ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup(pg);", true);

如果我执行以下操作:

ClientScript.RegisterStartupScript(
                   this.GetType(), "Popup", "ShowPopup('Test');", true);

它运行良好。它确实显示在弹出窗口中。知道我做错了什么吗。

ASP.NET C#使用ClientScript.RegisterStartupScript传递参数

问题是ShowPopup需要一个字符串值。

正确的代码

string pg = "Test";
ClientScript.RegisterStartupScript(this.GetType(), "Popup",
   string.Format("ShowPopup('{0}');", pg), true);

关于C#代码将生成以下有效javascript-

<script>
   ShowPopup('Test');
</script>

错误代码

ClientScript.RegisterStartupScript(this.GetType(), "Popup", 
   "ShowPopup(pg);", true);

请注意,上面的代码C#将生成以下无效Javascript-

<script>
   ShowPopup(pg); // Invalid Javascript code
</script>

如果使用更新面板,则可以使用:

string pg = "Test";
    ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('"+pg+"');", true);

其他明智的你可以使用

string pg = "Test";
     ClientScript.RegisterStartupScript
                (GetType(),Guid.NewGuid().ToString(), "alert('"+pg+"');",true);

在您的情况下是

string pg = "Test";
 ClientScript.RegisterStartupScript
            (GetType(),Guid.NewGuid().ToString(), "ShowPopup('"+pg+"');",true);

您也可以使用字符串插值:

string pg = "Test";
ClientScript.RegisterStartupScript(this.GetType(), "Popup", $"ShowPopup('{pg}');", true);