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

时间:2015-04-18 13:17:24

标签: javascript c# asp.net .net response

我有一个用户控件,上面有一个按钮,点击按钮我希望使用Javascript执行ScriptManager弹出并返回到父页面以执行response.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");
        }
    }
}

有人可以帮助我了解如何让我Javascript中的UserControl执行?我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

正如其他人所说,您的重定向首先发生。您可以使用以下任一方法进行重定向的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);