Incorporate a JavaScript message using C# code in the backend

I am looking for a code snippet to execute a JavaScript function called recordInserted() that displays an alert, within the add_Click method in my code-behind file. Here is the relevant section of my code:

protected void add_Click(object sender, EventArgs e)
    {
        String gradename = txt_gradename.Text;
        int allocatedclasses = Int32.Parse(txt_allocatedclasses.Text);
        String headid = txt_head_id.Text;
        int numberofstudents = Int32.Parse(txt_numberofstudents.Text);

        db = new DBConnection();
        db.getConnection();
        db.executeUpdateQuery("INSERT INTO Grade (GradeName,AllocatedClasses,GradeHeadID,NumberOfStudents) VALUES ('"+gradename+"','"+allocatedclasses+"','"+headid+"','"+numberofstudents+"')");

//I Need to call it from here before redirecting
        Response.Redirect("AdminReferenceGradeAdd.aspx");
    }

Your assistance with this would be greatly appreciated.

I have attempted the following without success:

Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted()",true);

Answer №1

It's important to note that simply using Response.Redirect may not work as intended because it redirects the response to a new page, preventing any client script from reaching the browser. A better approach would be to utilize Page.ClientScript.RegisterStartupScript in order to execute client-side code and then redirect to the desired page.

Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted();window.location.href='www.google.com'",true);

By using window.location.href, you can effectively redirect to your designated page ("yourpage.aspx").

Answer №2

Give this a shot:

ClientScript.RegisterClientScriptBlock(typeof(Page), "Invoke your function", "dataRecorded()", true);

Alternatively, attempt invoking a JavaScript function after a delay of one second:

ClientScript.RegisterClientScriptBlock(typeof(Page), "Invoke your function", "setTimeout('dataRecorded()', 1000)", true);

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

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Create a line connecting two divs using jQuery's DOM manipulation capabilities

Looking to connect two divs with a straight line, I stumbled upon jQuery DOM line, which appears to offer a more streamlined solution compared to jsPlump. I attempted to incorporate it into my code, but unfortunately, it's not working as expected. Be ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

Unable to parse the JSON information

After obtaining data from the World Bank for testing, I encountered an issue with deserialization while using the following query: http://api.worldbank.org/countries/IRL/indicators/SP.DYN.CBRT.IN? per_page=10&date=1960:2016&format=json [ { ...

Store the token securely in your browser's localStorage and set up interceptors

Struggling with saving the token in localStorage and pushing it in interceptors to send it with all requests. Currently, passing user data and token from Symfony controller to frontend, but facing roadblocks in saving the token in localStorage and settin ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

Add a user to a guild using Discord API

Hello, I'm currently working on integrating the Discord API to automatically add users to a guild upon login. However, I keep encountering a 401 Unauthorized error and I'm unsure of the reason behind it. Below is a snippet of my code: const data ...

How to quickly mask an array in C# to exclude specific indexes, similar to Python's approach

My Data Situation: //The dataset I have includes columns (second index) with the same value in each row (first index) double[][] dataSet = new double[][] { new double[] {1, 2, 3, 4}, new double[] {5, 6, 7, 4}, new double[] {8, 9, 10, 4}, }; My Desi ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

Scrolling a div automatically without affecting its parent element

On a page, I have a scrollable list of items that can be updated with a PUT request. Once the update is successful, another network request is made to fetch the updated list. The goal is to automatically highlight the recently updated item in the list. Al ...

Trying out the demonstration of the angular calendar in action

I am currently attempting to run the official example of the angular-calendar component found at http://angular-ui.github.io/ui-calendar/ Unfortunately, I am encountering an error that states: TypeError: undefined is not a function - it seems that the fun ...

jQuery alert: A TypeError was caught stating that the object being referred to does not have the 'dialog' method available

For a few days now, I have been tirelessly searching for a solution to this issue and it has caused me quite a bit of stress. My problem lies in echoing a JQuery popup script within php: echo '<link rel="stylesheet" href="http://code.jquery.c ...

The component briefly displays the previous state before updating in the Material-UI Alert component

Whenever there is an error from an API while a user is registering, an alert is displayed on the form page. To handle this, an Alert component was created: <Snackbar open={open} autoHideDuration={9000} onClose={() => { setOpen(f ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

What is the best method for saving query results to a text file containing multiple records?

I want to export specific fields from the query below to a Text file. But, I am encountering an issue where only one record is being displayed in the text file upon export. Additionally, I need to include non-query results in this text file as well. Furth ...