简体   繁体   English

C#中的JavaScript代码落后

[英]JavaScript code behind in c#

I have the following code in my cs file. 我的cs文件中包含以下代码。

private bool ValidateFirst()
{
    StringBuilder sb2 = new StringBuilder();

    sb2.Append(@"<script language='javascript'> var bContinue = true;");
    sb2.Append(@"bContinue = confirm(");
    sb2.Append("'some text here'");
    sb2.Append(@");");

    sb2.Append("if (bContinue) {");
    sb2.Append(this.Page.ClientScript.GetPostBackEventReference(this, "OKFinal"));
    sb2.Append("}</script>");

    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "ConfirmDialog", sb2.ToString());

    return false;
}

So what I wanted here is to display a confirm pop up on the page. 所以我想要在这里显示一个确认弹出页面。 The sb2.ToString() is working when I tested it on JSFiddle http://jsfiddle.net/2rbcsvh6/ (_doPostBack event will not work) but on my application, it won't display. 当我在JSFiddle http://jsfiddle.net/2rbcsvh6/上测试sb2.ToString()时,它可以工作(_doPostBack事件不起作用),但在我的应用程序中却无法显示。 The code is inside the screen controller action command. 该代码位于屏幕控制器操作命令中。

protected void screenController_ActionCommand(object sender, Web.Controls.CancelCommandEventArgs e)
{
    if (e.CommandName == ScreenController.OkCommand)
    {
        // this is the method that contains the script
        if (ValidateFirst)
        {
            this.Save();
        }
    }
}

The problem is by the time you embed the JS the page has already been loaded and rendered. 问题是当您嵌入JS时,页面已被加载并呈现。 You need to either run your code before the page has loaded ie Page_Load or alternatively wrap your JS in a function which you can then invoke from the client. 您需要在页面加载之前运行代码,即Page_Load或者将JS包装到一个函数中,然后可以从客户端调用该函数。

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

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