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

Transfer information from the client to the server using AJAX and PHP by

When attempting to post a JavaScript variable called posY to a PHP file, an error occurred with the message: Notice: Undefined index: data in C:\xampp\htdocs\Heads_in_the_clouds\submitposY.php The posY variable is defined in the JavaSc ...

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

Conversion of POST Body to Object in MVC is mysteriously hiding a thrown exception

Currently, I am implementing some basic validation in my model classes. Within my current project, there exists a model class as shown below: public class SimpleRequest { string _message; string _otherProperty; public Message { get { ...

Minimizing the size of a production application's bundle

In a production application I am working on, the bundle size is currently 8.06MB. # Output from npm build File sizes after gzip: 1.67 MB build/static/js/3.73cf59a2.chunk.js 794.29 KB build/typescript.worker.js 131.13 KB build/css.worker.js 1 ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

Error: null value cannot be scrolled into view - testing with react, jest, and enzyme

Utilizing react version 16.3.1, jest version 16.3.1, and enzyme version 3.3.0. Inside my React Class component, I have implemented a react ref to ensure that upon mounting the component, the browser scrolls back to the top of the page. class PageView ext ...

What is the best method to eliminate elements from a queue using JavaScript?

I recently attempted to incorporate a queue feature into my JavaScript code. I found some helpful information on this website. While I successfully managed to add items to the queue, I faced difficulties when attempting to remove items from it. var queue ...

Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code: $(document).ready(function() { $('input.required:text').focus(function() { $(this).css({'background ...

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

A guide on how to efficiently update and submit a reactive form with a single click of the submit button in Angular

Currently, I have a view component setup where clicking the edit button directs me to the register component for form updates using patchvalue. The issue that I am facing is that when I update and register the form using the same button, it creates anothe ...

Locate the database user based on any parameter provided in the request

I need to search for users in the database using any of three different fields. In Postman, I have set up the following paths: http://localhost:8082/api/users/617473029f80eda3643a7fdd http://localhost:8082/api/users/Michael http://localhost:8082/api/use ...

JavaScript application that features an audio player complete with a dynamic progress bar and customizable tags

Looking to create a custom audio player using HTML, CSS, and JS. The player should have basic functionality like a play button and progress bar. However, I want to allow users to add tags on the progress bar of the audio file, similar to how SoundCloud&apo ...

The absence of "_ssgManifest.js" and "_buildManifest.js" files in a Next.js application deployed on Google Cloud Platform was discovered

Upon opening the website, there are instances where the console displays the following errors: GET https://example.com/subpath/_next/static/9ufj5kFJf/_buildManifest.js [HTTP/3 404 Not Found 311ms] GET https://example.com/subpath/_next/static/9ufj5kFJf/_ss ...

Mapping objects in an array with Javascript

This code snippet is intended for a React Native Chat app. The structure of my data should look something like this: const chatData = [ { id: 1, name: 'John Doe', messages: [ {text: 'Hello', sentAt: 'time here' ...

Moving the words from textArea to each 'ol' element using JavaScript

When a word is entered in the textarea, it should be assigned to a specific class within an 'ol' tag. Each subsequent word will be placed in the next class sequentially. If there are no more words, the remaining classes should remain empty. <! ...