ASP.NET and C# Redirect

2020-08-09 09:13发布

问题:

I am working on a project for school, and this is an extra credit part. I have a project started in VS 2010 using master pages, and what I'm trying to do is get a "Submit" button to redirect people to the "MyAccounts.aspx" page. My current code for the ASP part for the button looks like this:

<asp:Button ID="btnTransfer" runat="server" Text="Submit"/>

I have tried adding in the OnClick option, as well as the OnClientClick option. I have also added this code to the Site.Master.cs file as well as the Transfer.aspx.cs file:

protected void btnTransfer_Click(object sender, EventArgs e)
{
    Response.Redirect(Page.ResolveClientUrl("/MyAccounts.aspx"));
}

When I run this and view the project in my browser, the whole thing runs fine, but when I click on the "Submit" button, it just refreshes the current page and does not properly redirect to the MyAccounts page. Anyone have any ideas for me?

回答1:

You are doing it almost correctly, you just haven't put the correct pieces together. On Transfer.aspx, your button should be:

<asp:Button ID="btnTransfer" OnClick="btnTransfer_Click" runat="server" Text="Submit"/>

and your code behind should be like what @KendrickLamar said:

protected void btnTransfer_Click(object sender, EventArgs e)
{
    Response.Redirect("~/MyAccounts.aspx");
}

The OnClick event tells it what to execute on post-back when the users clicks the button. This is in the code-behind for Transfer.aspx, not the site master.