繁体   English   中英

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

[英]ASP.NET C# use of ClientScript.RegisterStartupScript pass parameter

我有以下代码,应该在客户端脚本中调用一个名为ShowPopup的函数,但是由于某种原因,当我调用此函数时,什么也没有发生。

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

如果我执行以下操作:

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

它工作正常。 它确实显示在弹出窗口中。 任何想法我可能做错了。

问题是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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM