简体   繁体   English

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

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

I have the following code which should call a function called ShowPopup in my client side script but for reason, when I call this function nothing happens. 我有以下代码,应该在客户端脚本中调用一个名为ShowPopup的函数,但是由于某种原因,当我调用此函数时,什么也没有发生。

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

If I do the following: 如果我执行以下操作:

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

it works fine. 它工作正常。 It does show up in the popup. 它确实显示在弹出窗口中。 Any idea what I may be doing wrong. 任何想法我可能做错了。

The problem is ShowPopup is expecting a string value. 问题是ShowPopup需要一个字符串值。

Correct Code 正确的代码

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

About C# code will generate the following valid javascript - 关于C#代码将生成以下有效的 javascript-

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

Error Code 错误代码

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

Notice that above code C# will generate the following invalid Javascript - 请注意,以上代码C#将生成以下无效的 Javascript-

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

If you Used Update Panels Then You can Use: 如果您使用了更新面板,则可以使用:

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

Other Wise You can Use 您可以使用的其他明智

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

in your case 在你的情况下

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