Javascript - 与 C# Response.Redirect() 一起使用时不执行



我有一个带有按钮的用户控件,单击按钮时,我想使用ScriptManager执行Javascript弹出窗口并返回到父页面以执行响应.redirect。但由于某种原因,我的Javascript没有被执行。我注意到,如果我删除父级上的响应重定向,Javascript执行工作正常。

下面是我的代码:

用户控件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RegisterDemo
{
    public partial class RegisterUserControl : System.Web.UI.UserControl
    {
        public delegate void customHandler(object handler);
        public event customHandler SendtoParent;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void usercontrolbutton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "validator", "alert('Error');", true);
            SendtoParent(sender); 
        }
    }
}

父页面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RegisterDemo
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MyUserInfoBoxControl.SendtoParent += new RegisterUserControl.customHandler(onusercontrolevent_click);
        }
        protected void DemoButton_Click(object sender, EventArgs e)
        {
            //ScriptManager.RegisterStartupScript(this, GetType(), "validator", "alert('u click this button');", true);
        }
        protected void onusercontrolevent_click(object sender)
        {
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "event", "alert('event completed');", true);
            Response.Redirect("www.google.com");
        }
    }
}

有人可以帮我找出如何执行UserControl中的Javascript吗?我在这里错过了什么?

正如其他人所说,您的重定向首先发生。您可以使用以下任一到 JS 方法进行重定向

// similar behavior as an HTTP redirect
window.location.replace("http://google.com");
// similar behavior as clicking on a link
window.location.href = "http://google.com";

创建新函数

function Validation() {
    alert('Error');
    // similar behavior as an HTTP redirect
    window.location.replace("http://google.com");
    // similar behavior as clicking on a link
    window.location.href = "http://google.com";
}

并改变你ScriptManager

ScriptManager.RegisterStartupScript(this, GetType(), "validator", "Validation();", true);

您可以使用 JavaScript 进行重定向。例如,window.location.href = ""而不是使用代码隐藏中的Response.Redirect

最新更新