When an alert box is displayed in ASP.NET, it causes a redirection to a blank page before returning to the original page

On my ASP.net page, I have 3 input boxes and a button. When the button is clicked, the code below is executed.

 protected void buttonId_Click(object sender, EventArgs e)
    {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("https://visitor2.constantcontact.com/api/signup");

            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array.
            string postData = "some secrect key";
            postData = postData + "&email=" + emailadd.Text;
            postData = postData + "&first_name=" +fname.Text;
            postData = postData + "&last_name=" + lname.Text;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();

            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();

            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            if (responseFromServer.ToLower().Contains("success"))
            {
                //signup complete
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Thanks for signing up!')", true);
            } else {
                //error occured
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Whoops! Something went wrong. Please try again.')", true);
            } 
    }

Upon running the following line of code, the webpage redirects to a blank page and displays the alert.

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Thanks for signing up!')", true);

After clicking the OK button on the alert message, it automatically navigates back to the original page.

How can I prevent it from going to the blank page? I want the alert to show on the original page without navigating back and forth.

This is my HTML structure

<div class="footer_subscribe">
                            <asp:TextBox ID="fname" runat="server" class="name" value="First Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'First Name';}"></asp:TextBox>
                            <asp:TextBox ID="lname" runat="server" class="name" value="Last Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Last Name';}"></asp:TextBox>
                            <asp:TextBox ID="emailadd" runat="server" class="name" value="Join our mailing list" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Join our mailing list';}"></asp:TextBox><br>

                            <asp:Button ID="buttonId" OnClick="buttonId_Click" class="btn btn-info sub1" runat="server" Text="SUBSCRIBE"></asp:Button>
                        </div>

Answer №1

If you haven't already, consider using RegisterStartUpScript instead of RegisterClientScriptBlock. Give this a try:

private void DisplayPopupMessage(string message)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showpopup",     sb.ToString(), true);
}

and then DisplayPopupMessage("Greetings!")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

What are the differences between displaying JSON data on a Flask interface compared to a Django interface

Currently, I am looking for the simplest method to display data on a web interface using either Flask or Django (whichever is easier). I already have some sample JSON objects available. Could anyone provide recommendations on how to achieve this and whic ...

Class-validator does not have any associated metadata

Struggling with implementing a ValidationPipe in my code, I consistently encounter the warning "No metadata found. There is more than one class-validator version installed probably. You need to flatten your dependencies" when sending a request. The struct ...

Secure javascript to manage cookies in PHP

Utilizing html and javascript for the client side, and php for the server side. Upon user sign up, a unique userID is generated by the server and stored in the database. On the server, I implement setcookie to allow users to stay logged in across different ...

Send the `this` value when calling the constructor of the subordinate module - designated typing

Help needed for upgrading code from JavaScript to TypeScript and dealing with circular dependencies. Directory: Main.ts Helper.ts Main Module: import Helper from "./Helper" export default class Main { helper: Helper constructor() { ...

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

"Create visually appealing designs with Material UI by incorporating round images in Card

Recently delving into full stack development, I've been experimenting with coding to enhance my understanding of frontend using React JS and Material UI. In the process, I incorporated a card component to display posts from the backend. However, I enc ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

Determining the clicked button using this.Request.Form: a comprehensive guide

My current setup involves utilizing .net 1.1 In one of my pages, I have several ImageButtonClientSide Controls along with other buttons that trigger a postback. My goal is to determine which control has been clicked when the page performs a postback within ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Trouble transferring data between sibling components in Vue.js

In my setup, there are three components where one acts as the parent to the others. I am attempting to pass an object named talk between sibling components by emitting it through an event from FollowedBrowser to LeftBar, and then passing it via props from ...

Issue with switching iframes using WebdriverJS/ProtractortoggleClass is not functioning

For over a week now, one of my automation test cases has been stuck due to a lazy loaded iframe (the iframe is inserted into the DOM only after clicking a link). Here's an excerpt from my code: driver.get("my url"); driver.findElement(By.linkText(&ap ...

A comprehensive guide on connecting an HTML Label to a sqldatareader

Trying to associate a label with a datareader has been challenging. When dealing with an input type="text", I can easily accomplish something like this: NameLabel.Value = reader["Name"].ToString(); - <label id="lblName" runat="server"></label&g ...

Creating a Server-side binding for a DropDownList item in order to retrieve multiple date values

In my project, there is a dropdown list that is populated with data from a datasource during the page load process. When a user selects an item from the dropdown list and triggers the SelectedIndexChanged event, I need to retrieve multiple values associat ...

Sails has not been installed yet

Despite attempting multiple methods found on the internet, I am unable to successfully start Sails after installation. Every time I input "sails lift", it returns an error stating "sails not installed". Could this issue be related to hardware or version ...

Execute JavaScript AJAX Request On Page Load

I am facing an issue with creating an onload event in which an AJAX function needs to be called and passed a value. The challenge lies in the fact that I have both my header and footer split into sections via PHP, therefore I cannot place it on the body ta ...

Find the child only when the value changes in Firebase using Vue

I'm currently developing my first application using Vue and Firebase. On one page, users can create a post and send it to the real-time database with name, email, picture, and status. In another page (the admin page), you have the option to publish ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...