我目前卡住。我有与注册或保存记录按钮一个WebForm。 我想是有它显示一个JavaScript警告,然后重定向到一个页面。 下面是我使用的代码

protected void Save(..)
{   
    // Do save stuff
    DisplayAlert("The changes were saved Successfully");
    Response.Redirect("Default.aspx");
}

此代码只是重定向而不给予成功保存的提示。

下面是我DisplayAlert代码

 protected virtual void DisplayAlert(string message)
    {
        ClientScript.RegisterStartupScript(
                        this.GetType(),
                        Guid.NewGuid().ToString(),
                        string.Format("alert('{0}');", message.Replace("'", @"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
                        true
                    );
    }

谁能帮我找到了解决这个?

由于

有帮助吗?

解决方案

您不能做一个Response.Redirect的,因为你的JavaScript警告将永远不会显示。最好是有你的JavaScript代码实际上做windows.location.href='default.aspx'做重定向显示警报之后。是这样的:

protected virtual void DisplayAlert(string message)
{
    ClientScript.RegisterStartupScript(
      this.GetType(),
      Guid.NewGuid().ToString(),
      string.Format("alert('{0}');window.location.href = 'default.aspx'", 
        message.Replace("'", @"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
        true);
}

其他提示

在DisplayAlert方法将客户端脚本对当前正在执行页面请求。当你打电话的Response.Redirect,ASP.NET发出HTTP 301重定向浏览器,因此开始在那里注册的客户端脚本不再存在,新的页面请求。

由于您的代码是在服务器侧执行的,也没有办法来显示警报客户端和执行重定向。

此外,显示一个JavaScript警告框可以迷惑用户的精神的工作流程,直列消息会更优选。也许你可以在信息添加到会话和Default.aspx页面请求显示这一点。

protected void Save(..)
{   
    // Do save stuff
    Session["StatusMessage"] = "The changes were saved Successfully";
    Response.Redirect("Default.aspx");
}

然后,在后面Default.aspx.cs代码(或一个共同的基页类,所以会发生这种情况的任何页上,或甚至在主页):

protected void Page_Load(object sender, EventArgs e)
{
    if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
    {
        string message = (string)Session["StatusMessage"];
        // Clear the session variable
        Session["StatusMessage"] = null;
        // Enable some control to display the message (control is likely on the master page)
        Label messageLabel = (Label)FindControl("MessageLabel");
        messageLabel.Visible = true;
        messageLabel.Text = message;
    }
}

代码未经测试,但应该指向你在正确的方向上

此运行完美:

string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{       
    // Do save stuff    
    ShowMessageBox();  
} 

private void ShowMessageBox()
{        
    string sJavaScript = "<script language=javascript>\n";        
    sJavaScript += "var agree;\n";        
    sJavaScript += "agree = confirm('Do you want to continue?.');\n";        
    sJavaScript += "if(agree)\n";        
    sJavaScript += "window.location = \"http://google.com\";\n";        
    sJavaScript += "</script>";      
    Response.Write(sJavaScript);
}  
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top