每次页面加载时停止执行 C# 代码

发布于 2024-11-29 09:07:18 字数 363 浏览 1 评论 0原文

我的代码隐藏文件中有一个公共字符串,当我准备好时,我打算从 javascript 调用它。但是,由于它并不真正与特定事件相关,因此它只是在每次页面加载时触发。我会将其设置为仅触发 if(IsPostBack) 但我使用的控件(出于许多其他原因)是一个输入 type=button,因此页面永远不会真正执行回发,这意味着代码永远不会触发。

我如何

public string dontExecuteYet()
 {
  Do some server side stuff
  Then redirect on delay
  return string
  }

在我的代码隐藏中添加类似以下内容的内容,使其在我告诉它之前不会运行?

I have a public string in my code behind file that I intend to call from javascript when I'm ready for it. However, since it's not really tied to a particular event, it just fires every time the page loads. I would set it to only fire if(IsPostBack) but the control I'm using (for many other reasons) is an input type=button so the page never really does postback meaning the code will never fire.

How do I have something like:

public string dontExecuteYet()
 {
  Do some server side stuff
  Then redirect on delay
  return string
  }

in my Code Behind such that it doesn't run until I tell it to?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼趣 2024-12-06 09:07:18

您可以使用 Page 方法和 AJAX 来完成此操作,如下所示。

http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm

代码仅当您使用 javascript 调用它时才会执行

......

该 。

实际上,您还可以通过添加 onclick="javascript:__doPostBack('eventargument','eventvalue');" 强制在输入按钮上进行回发 (如果你有控制权的话)

You can do this with a Page method and AJAX like this.

http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm

That code executes only when you call it with javascript

....

....

Actually you can also force a postback on the input button with adding onclick="javascript:__doPostBack('eventargument','eventvalue');" (if you have that control over it)

甜尕妞 2024-12-06 09:07:18

如果您最终需要访问代码(假设在初始 Page_Load 之后),您不能只执行以下操作:

if (!Page.IsPostBack)
{
    this.MyPublicString = "Hello World!";
}

在 JavaScript 中:

var publicString = "<%= this.MyPublicString %>";

If you need to access the code, eventually (assuming after the initial Page_Load), can't you just do something like this:

if (!Page.IsPostBack)
{
    this.MyPublicString = "Hello World!";
}

And in your JavaScript:

var publicString = "<%= this.MyPublicString %>";
旧伤还要旧人安 2024-12-06 09:07:18

我同意你可以在其中使用 AJAX,但如果你不需要异步,只需使用查询字符串,如下所示:

if(Request.QueryString["execute"] == "yes")
{
     dontExecuteYet();
}

在 javascript 中,你只需要在按下按钮时触发此代码:

window.location = "yoursite.com?execute=yes";

I agree you can use AJAX in this, but if you don't need this to be async, just use a query string, like so:

if(Request.QueryString["execute"] == "yes")
{
     dontExecuteYet();
}

and in the javascript, you just need for this code to fire when the button is pressed:

window.location = "yoursite.com?execute=yes";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文