Issue with ClientScript.RegisterStartupScript function

I've exhausted my search efforts on both SO and Google, but I'm still unable to get this particular code working. The issue lies within the codebehind click event of a "Cancel" button in my ASP.NET application. Despite my attempts, the popup window refuses to close. Any suggestions?

try
{
    if (btnCancel.Text == "Close")
    {
        String csName1 = "PopupScript";
        Type csType = this.GetType();

        ClientScriptManager cs = Page.ClientScript;
        if (!cs.IsClientScriptBlockRegistered(csType, csName1))
        {
            ClientScript.RegisterStartupScript(GetType(), "ClosePopup", "window.close();", true);
        }
    }
}  

Update: Upon inspecting the source page post-postback, I only see the following related code:

//<![CDATA[
(function() {var fn = function() {$get("ToolkitScriptManager1_HiddenField").value = '';Sys.Application.remove_init(fn);};Sys.Application.add_init(fn);})();window.close();
document.getElementById('ValidationSummary1').dispose = function() {
    Array.remove(Page_ValidationSummaries, document.getElementById('ValidationSummary1'));
}

Answer №1

Here is an alternative solution for you

Add this code snippet:
ScriptManager.RegisterStartupScript(this.Page, GetType(), "ClosePopup", "window.close();", true);

You can also give this a try

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "ClosePopup", "window.close();", true);

Wishing you a great day ahead.

Answer №2

Due to the inability to make the ClientScript function work as needed, I had to come up with a workaround solution using the following code snippet:

function closeWindow() {
    //Close the window if txt = 'cancel';
    GetRadWindow().Close();
}

<td align="center"><asp:Button runat="server" ID="btnClose" Text="Close" 
        OnClientClick="closeWindow();return false;" onclick="btnClose_Click"/></td>

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

"An error is occurring in JavaScript: $ is not defined, but I am uncertain of the reason for it

I am attempting to test a code involving html, css, and javascript but it is not functioning as expected. I am unsure of the reason. click here to view image Create a random name generator with customizable input names and display the winner selected by t ...

I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN. const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

Despite being queried, the new content on Hygraph is still not appearing

Currently, I am in the process of developing my personal portfolio website using NextJS and incorporating a blog feature with hygraph for post storage (which is derived from the default nextjs blog setup). However, I have stumbled upon an unusual issue. Af ...

When Node.js is executed as a script, how is the context of `this` determined?

When using the node REPL: $ node > var x = 50 > console.log(x) 50 > console.log(this.x) 50 > console.log(this === global) true It all seems clear when working in this environment. However, things take a turn when running a script: $ cat test ...

How DataTables Handles Loading and Rendering Time Delay

Utilizing DataTables in conjunction with Bootstrap 4 for client-side processing while displaying approximately 2,000 records. The loading time is acceptable, but upon refreshing the page (F5), I observe an unformatted DataTable briefly appearing. It seems ...

Transforming a React page into a JSON format and then having the ability to change that JSON back into a React page

Is there a way to easily transform a React page into JSON format so that after saving it, I can render the same page with all its details intact? import React from 'react'; import { useState } from 'react'; const Form = () => { ...

CSS styling can be used to generate a line break above and below a drop-down menu

While working on my CSS drop down menu, I noticed that it was generating unwanted line breaks before and after the dropdown. Below is the HTML code: <body> <!--nav class="navi"--> <div class="navi" id="navi"> <ul> <li& ...

What is the purpose of linking database tables?

In my current database model, I have various tables that store business logic data. One of these tables includes a user table that holds the UserID. The code retrieves data from these tables and creates a json string used in the application. To avoid redun ...

Using Javascript's regular expressions to add double quotes around JSON values that are not already enclosed in quotes

Dealing with improperly formatted JSON values can be a challenge. The response I am working with is from a Java Servlet, specifically a hashmap, over which I have no control. Initially, it looked like this: { response={ type=000, products=[{id=1,name=prod ...

Executing a function by clicking on an element with the `ng-click` directive within a Bootstrap modal

I'm working on an app that allows users to submit posts for review. When a user clicks the add post button, I have a Bootstrap modal pop up to confirm their choice. Within this modal, there is a "confirm" button that should trigger a function. Strang ...

Exploring the method of retrieving a wrapped object's property within a Node.js addon

Currently, I am dealing with the following JavaScript code snippet: var c = new addon.Component(); c.ComponentLength = 3 I am struggling to figure out how to structure my addon in order to execute the above code successfully. I have already gone through ...

Issues arise when attempting to execute a query using a Guid as a parameter in ASP.NET and C#

In the process of developing a booking platform, one crucial feature is allowing logged-in users to view their previous reservations. To achieve this functionality, I am utilizing a DataList in conjunction with a TableAdapter. Firstly, I obtain the user&a ...

Error in Vue.js: "Trying to access properties of an object that is undefined (specifically '$refs')"

When we trigger methods from a parent component in a child component, we use the following code: await this.$refs.patientinputmask.$refs.patientpersonaldata.ChangePersonalData(); await this.$refs.patientinputmask.$refs.patientaddressdata.SavePersonalAddres ...

Instructions on extracting the initial 16 bytes of data from a base64 decoded string

Looking to extract the first 16 bytes of data from a Base64Decode string. Here is my code snippet, seeking suggestions on how to achieve this: let base64Encodeded = "Hf8Qqpr1klv+Mjle4v0yfOXbQpiXwICyEDF4bYGt/ve7h9a1cEqd5z3QpvnPMLzRpDxSBEutaOdh8SN/Yi9 ...

ng-click="showInventory()" onClick="currentTemplate='/inventory.html'" Not

I'm facing an issue with my menu list. When I apply the ng-repeat directive, it seems to not work properly. However, when I remove the ng-repeat, everything functions as expected. <div class="reports_header_tabs_holder"> <span ng-repea ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Database Error on the Scaffold

Currently, I am working on a .NET Core 2.0 solution that consists of two projects. One project is a SQL Server database project while the other one is a .NET Core 2.0 console app project. In the console project, I had been using the scaffold command (show ...

The function getElementbyId is not recognized

My JavaScript code is supposed to change the color of a button, but I'm running into an issue where it says that getting the button is not a function. Strangely enough, the same function (with the same capitalization and case) works perfectly just a f ...