The JavaScript function on the master page is not being triggered by the code behind

Two pages are named: Abc.aspx and popupAbc.aspx

On the Abc.aspx page, there is a button that opens popupAbc.aspx as a pop-up:

<asp:Button ID="btnOpenChildAbcPopup" runat="server" Text="Open" UseSubmitBehavior="false" CausesValidation="False" OnClick="btnOpenChildAbcPopup_Click" />

Code Behind:

protected void btnOpenChildAbcPopup_Click(object sender, EventArgs e)
        {
            string url="../popupAbc.aspx";
            ScriptManager.RegisterStartupScript(Page, GetType(), "alert", "OpenChildAbcPopup('" + url + "');",
                    true);
        }

function OpenChildAbcPopup(url) {
                    $.fancybox({
                        'onStart ': function () { $.fancybox.hideActivit() },
                        'onComplete': function () { $.fancybox.hideActivity() },
                        'titleShow': 'true',
                        'titlePosition': 'over',
                        'titleFormat': 'formatTitle',
                        'href': url,
                        'type': 'iframe',
                        'width': '1000',
                        'height': '500',
                        'fitToView': false,
                        'autoSize': false,
                        'hideOnOverlayClick': false,
                        'hideOnContentClick': false,
                        'overlayOpacity': 0.7,
                        'enableEscapeButton': false,
                        'closeEffect': 'none' 
                    });
                    $.fancybox.hideLoading();
                    return false;
                }

Everything works perfectly up to this point. However, there is an issue within the popupAbc.aspx.

In the popupAbc.aspx page, there is a save button that, upon clicking, should call a JavaScript function on the master page, but it is not working.

This code is in the popupAbc.aspx page:

  <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MyMaster.Master" CodeBehind="popupAbc.aspx.cs" Inherits="popupAbc.aspx" %>

<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" UseSubmitBehavior="true"  ValidationGroup="p1" />

 protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Save form data in database and then call a JavaScript function on the MyMaster page
            ScriptManager.RegisterStartupScript(Page, GetType(), "Js", "ExitMyCurrentFancyBox();", true);
        }

An error is thrown in the console saying that ExitMyCurrentFancyBox is not defined.

When the ExitMyCurrentFancyBox function is moved to the popupAbc.aspx, it successfully calls. However, when placed on the master page, it does not work.

function ExitMyCurrentFancyBox() {
                alert()
            }

Note:The Abc.aspx page uses an update panel, while popupAbc.aspx does not use one.

Any suggestions on why the JavaScript function is not calling when placed on the master page and how to make it work?

I have tried various methods, but none of them seem to be effective:

 // ScriptManager.RegisterStartupScript(Page, GetType(), "alert", "ExitMyCurrentFancyBox();", true);
               // ScriptManager.RegisterStartupScript(Page, GetType(), "alert", "ExitMyCurrentFancyBox();", true);
                //ClientScript.RegisterClientScriptBlock(GetType(), "sas", "CloseFancyboxtl();", true);
              //  ScriptManager.RegisterStartupScript(this, this.GetType(), "ntmtch", "ExitMyCurrentFancyBox();", true);
          //  ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "ExitMyCurrentFancyBox();", true);
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "ExitMyCurrentFancyBox;", true);
            ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), Guid.NewGuid().ToString(), "ExitMyCurrentFancyBox();", true);

Answer №1

Providing a solution as requested.

To incorporate javascript alert functionality, you can add the following method to your MasterPage:

public void DisplayAlert(){
    Response.Write("<script language='javascript'>alert('This is a custom alert message');</script>");
}

Then in your content page:

this.Master.DisplayAlert();

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

Array scripts are removed once data has been extracted from the CSV file

Having trouble reading a CSV file using file reader in Javascript. I wrote a script that declares arrays and updates them as the file is read. However, once the reading is complete, all data from the arrays gets wiped out. I'm quite new to JS and can& ...

Tips for using jQuery to load JSON data from a backing bean within a customized JSF component

What is the most efficient way in JSF 2.2 to load JSON data from a backing bean into a JavaScript program that runs in a browser? Currently, I am transitioning a messy, iframed visjs network graph to JSF 2.2 - Primefaces 6.1. All our custom UI components ...

Why do I receive the error message "Error: Objects are not valid as a React child (found: [object Promise])" in NextJS13?

I'm feeling overwhelmed by this issue and unsure of how to resolve it. Here is the code that is causing trouble: 'use client' import React, { useState } from 'react' import AnimatedDiv from '../../../(shop)/(components)/animat ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

Using JavaScript to identify the unlock screen on a website

I've been searching everywhere for a solution to my issue, but I haven't had any luck with Google or other websites. I'm currently working on creating a mobile website and I need assistance with redirecting users to the homepage in such a w ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Enroll in the Castle Windsor Logging Facility now!

I am currently exploring IOC and Castle Windsor for the first time. I want to implement the logging feature provided by Castle as outlined in their official documentation. Following the recommendations in the documentation, I am attempting to register the ...

Determining if a date has passed using moment.js, focusing solely on the date

Is it possible to determine if a date has passed based solely on the date itself? Currently, I am using !moment(moment().format("LLL")).isBefore(moment.unix(data.dueDate._seconds).format("LLL")). However, this approach also takes into account the time. F ...

What is the reason for the inability to debug the JavaScript function from an ASPX file?

I need to insert a debug point in my JavaScript function within the ASPX source file. However, when I write the keyword "debugger" inside the function and click the update button, the debugger is not being triggered. All I want is for the debugger in the ...

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

Multiple date selectors within a single table

I have incorporated the Bootstrap 4 datetimepicker library into my project, which can be found at . I am facing an issue where I have a table on my page with multiple rows, each containing a datepicker. The problem is that while the first datepicker functi ...

Best technique for quick and secure server side image resizing

I have successfully implemented code using GDI (System.Drawing), but now I am considering transitioning to either System.Windows.Media.Imaging or ImageMagick. I want to ensure that the new method is memory efficient, thread-safe, multi-threaded, and capab ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

Remove a Row from a Table by Clicking a Button with Ajax

I currently have an HTML table with 4 columns: SKU Group, Group_ID, Edit button, and Delete button. My focus at the moment is on implementing the delete functionality. I want it so that when the delete button is clicked, a confirmation box appears. If "OK" ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

What is the best way to have Protractor pause until a specific promise is resolved?

I am having an issue with my website where clicking a button triggers an angular service that returns some data to be displayed on the page. I need to write an angular test that clicks the button, waits for the promise to resolve, and verifies that the dat ...

Launching a modal within a Scala HTML list

When attempting to open a modal window within a list of items (specifically attachments), I am encountering difficulties retrieving the record ID from the list. The new modal window is opened with Scala, but I consistently receive an error stating that t ...

What is causing the discrepancy between the SQL outputs of these equivalent expression trees?

In my entity project, I am utilizing two expressions for a global query filter. Firstly, there is the compile-time expression: Expression<Func<RandomTable, bool>> test = c => AuthorisedUsers.Any(b => b.RandomTableId == c.RandomTableId &a ...

Methods to notify the user in a C# Windows Form Application when attempting to close a tab where the file no longer exists

My latest project involves developing a notepad application with a tabbed interface using C# WinForms. One feature I am eager to implement is the ability to detect and handle situations where a file has been deleted by another program. Specifically, if a ...