Changing the value of a JavaScript variable within the .Net Codebehind

I've run into an issue where I need to update a JavaScript variable after post-back. My initial approach was to use the ClientScript.RegisterStartupScript function, which worked fine during the first page load but failed on subsequent postbacks. I included the following line in the page_load function and suspect that the key cannot be added multiple times. The structure of my setup involves a master page and content page, with this call originating from the content page.

ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Error !!!');</script>");

Is there a more efficient way to invoke a JavaScript function from the back-end?

Appreciate any help or advice.

Answer №1

Check out this approach:

Syntax

   public void AddScriptOnSubmit (
        Type type,
        string key,
        string script
)

Usage

By adding this code during page load, the script will execute whenever the form is submitted.

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
        {
            script.AddScriptOnSubmit(this.GetType(), "SubmitScript", "alert('Submit Clicked')");
        }

Take a look at the following code snippet

protected void Page_Load(object sender, EventArgs e)
    {    
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
     {
          script.AddScriptOnSubmit(this.GetType(), "SubmitScript", "return confirm('Are you sure to continue')");
     }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write("Form has been Submitted.");
    }

Answer №2

One way to include the variable assignment in your javascript code is by placing an asp:Literal within a script block on your aspx page.

In your code behind, simply assign the variable value to the literal as text. This will ensure that it is rendered as part of your javascript code.

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

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

Using ElectronJS requires the usage of the import keyword to load ES Modules

I've recently delved into Electron development by exploring the Electron Docs. I opted for ES6 syntax with import/export, while the documentation showcased the use of require. To align with ES Module standards, I updated my package.json file with typ ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

Scale up the font size for all text on the website uniformly

Recently, I decided to switch a website's font to a non-web typeface. However, I quickly realized that the font was extremely thin and difficult to read. I attempted a simple CSS fix using * { font-size:125% }, but unfortunately, it did not have the d ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Creating a dynamic C# ASP.NET MVC login form with AJAX functionality

Trying to implement the MVC Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId="updateajax" }) with a <div id=updateajax/> specified as the target location. The issue I am facing is that even after successful login, the entire page ...

Parsing HTML to access inner content

Currently, I have integrated an onClick event to an anchor tag. When the user interacts with it, my objective is to retrieve the inner HTML without relying on the id attribute. Below is the code snippet that illustrates my approach. Any assistance in acc ...

Invoking a PHP class through an AJAX response handler code

I'm attempting to access a PHP-File using AJAX. When I use a basic PHP-File like this: <?php header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: must-revalidate, pre-check=0, no-store, no-cache, max-age=0, pos ...

Is there a way to identify the top five elements that are most frequently occurring in the array?

I've successfully found the element that appears the most in an array, but now I'm facing a new challenge where I need to identify the top 5 elements that appear most frequently. Here is the array: [ "fuji", "acros", &q ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

Hide the Bootstrap slide menu with jQuery by clicking anywhere on the screen

Here is a Fiddle link: https://jsfiddle.net/r94dq2e4/ I have incorporated a slide-in menu from the left in my website using Twitter Bootstrap version 3. The menu appears when the navbar toggle button is clicked. This is the jQuery code responsible for ...

The .NET service is encountering a 500 internal error and is returning a "missing parameter" message when receiving HttpWebRequest POSTS, although the test form is

While using a simple .NET service (asmx) everything works smoothly when invoking it via the test form. However, encountering a WebException "System.Net.WebException: The remote server returned an error: (500) Internal Server Error" occurs when trying to in ...

Display JSON information in a grid using JQuery

I'm on the lookout for a simple json grid plugin to make my life easier. I need to populate a grid using JSON/Ajax, but the catch is that the amount of data or columns will vary each time, so it needs to be able to adapt accordingly. For example, a p ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...

Guide on creating multiple instances of vue-multiselect with a simple button click

I am trying to implement a vue-multiselect dropdown with the addition of a new dropdown upon clicking an "add more" button. However, I am currently unsure of the best approach to achieve this. Problem/Question: When adding 2 dropdowns, if the same option ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

Error encountered in Three.js: ShaderPass.js is unable to read the property 'prototype' of undefined

I'm currently facing an issue while trying to implement a basic GlitchPass in a Three.js demo. I keep encountering the error message Uncaught TypeError: Cannot read property 'prototype' of undefined at ShaderPass.js. For this particular dem ...

Discover the size of objects in three.js

Looking for a way to determine the dimensions of a mesh in three.js? I have Collada (.dae) files and need to know their size in units (x,y,z). I've heard about using geometry.computeBoundingBox(), but could use more guidance on how to implement it. ...