简体   繁体   English

在代码隐藏中从 Page_Load 调用 javascript 函数

[英]Calling a javascript function from Page_Load in code-behind

如何在代码隐藏中从 Page_Load 方法调用 aspx 页面中的 javascript 函数?

The simple answer is, you can't.简单的答案是,你不能。 The code in the Page_Load method executes on the server, javascript executes on the client. Page_Load 方法中的代码在服务器上执行,javascript 在客户端上执行。

If what you want to do is add a call to a javascript method, in the Page_Load so that once the page is loaded by the browser, the javascript executes, then you can use the ScriptManager:如果您想要做的是在 Page_Load 中添加对 javascript 方法的调用,以便在浏览器加载页面后执行 javascript,那么您可以使用 ScriptManager:

if (myConditionForAddingCallToJavascriptIsMet)
{
    Page.ClientScript.RegisterClientScriptBlock(typeof(ScriptManager), "CallMyMethod", "myMethod();");
}
else
{
    // Do something else, add a different block of javascript, or do nothing!
}

To use this, you'll need to have an <asp:ScriptManager> element in your markup for it to use (if memory serves, an exception will be thrown if you don't have one).要使用它,您需要在标记中包含一个<asp:ScriptManager>元素以供使用(如果没记错的话,如果没有,将抛出异常)。 The text "CallMyMethod" is used by the ScriptManager to uniquely identify the script that it injects for you, and the text "myMethod();" ScriptManager 使用文本“CallMyMethod”来唯一标识它为您注入的脚本,以及文本“myMethod();” is embedded, so you'll end up with an additional script element in your page similar to this:已嵌入,因此您最终会在页面中添加一个类似于以下内容的附加脚本元素:

<script language="javascript" type="text/javascript">
    myMethod();
</script>

The easiest way is to use the page's ClientScript property.最简单的方法是使用页面的 ClientScript 属性。 You can register some code to run when the page loads using something like您可以使用类似的方法注册一些代码以在页面加载时运行

ClientScript.RegisterStartupScript(GetType(), "hiya", "alert('hi!')", true);

See http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx for more info.有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

This should be available from a child control by tacking "Page."这应该可以通过添加“页面”从子控件中获得。 onto the beginning of the code above.到上面代码的开头。

Why would you want to do this?你为什么想做这个? What's the purpose?目的是什么?

Anyway you can do the following, but I DON'T recommend it !!!无论如何,您可以执行以下操作,但我不推荐它!!! :

     protected void Page_Load(object sender, EventArgs e)
    {
         string pagename = "Test.aspx"; 
         String scriptString = "<script language=JavaScript> function DoClick() {"; 
         scriptString += " window.showModalDialog('" + pagename + "' )}"; 
         scriptString += "</script>";            

if(!this.IsStartupScriptRegistered("Startup")) //This is **not** a good practice
this.RegisterStartupScript("Startup", scriptString); 
    }

Can you supply with more information of what you want to achieve to get better answer..您能否提供有关您想要实现的目标的更多信息以获得更好的答案..

Shide's solution works.实德的解决方案有效。 The problem is if you want to run your piece of code only on postback, for example.问题是,例如,如果您只想在回发时运行您的代码段。 The solution I found was to use a "cookie": I verify if cookie x exists, if it doesn't I run the javascript code and set the cookie.我找到的解决方案是使用“cookie”:我验证 cookie x 是否存在,如果不存在,我运行 javascript 代码并设置 cookie。 When you hit refresh, the cookie will be found so the piece of code won't run.当您点击刷新时,将找到 cookie,因此该段代码不会运行。

function pageLoad() {
   if(localStorage.getItem("cookie") === null) {
      localStorage.setItem("cookie", true);

      //run code
   }
}

Any code you need to run every single time just leave it out of the if statement.您需要每次运行的任何代码都将其排除在 if 语句之外。

If you just want to call a JavaScript function ( and do not need to pass something from code-behind, then use this...)如果你只想调用一个 JavaScript 函数(并且不需要从代码隐藏中传递一些东西,那么使用这个......)

  • document.onload = function () { your-function(); document.onload = function () { your-function(); }; };

  • window.onload = function () { your-function(); window.onload = function () { your-function(); }; };

  • document.readyState = function () { your-function(); document.readyState = function () { your-function(); } }

    ... depending on your specific requirements. ...取决于您的具体要求。

Hope this makes sense to you & answers your question.希望这对您有意义并回答您的问题。

this is a little trick i found myself without having server side code .这是我发现自己没有服务器端代码的一个小技巧。 that function will be called when the page loads (can be used with an update panel) :该函数将在页面加载时调用(可与更新面板一起使用):

<script>
function pageLoad() {
        //Do your stuff
        }
</script>

it is unknown and yet works like a charm它是未知的,但就像一个魅力

请试试这个代码:

  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "test();", true);

You need to use Register client Script:您需要使用注册客户端脚本:

I do it in a Page Load method:我在页面加载方法中执行此操作:

if (!this.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "HelpScript"))
{
  var scriptSource = "function ShowHelp() { alert(""); };\n";
  ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true);
}

but I don't think it's recommended但我认为不推荐

I mean... you can do this, and it'll work.我的意思是……你可以这样做,而且它会起作用。 But for me the only good reason of inserting a script from asp.net page is to get some client side features of server controls.但对我来说,从 asp.net 页面插入脚本的唯一充分理由是获得服务器控件的一些客户端功能。

So for example to get an instance of control:因此,例如获取控制实例:

var myControlId = this.control.ClientID;

But writing entire javascript functions and logic on the server side is not comfortable when you need to change it or debug it (for me it's hardcoded string).但是当您需要更改或调试它时(对我来说它是硬编码的字符串),在服务器端编写整个 javascript 函数和逻辑并不舒服。

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

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