Tips for displaying an alert within an asynchronous method in ASP.NET

Is there a way to trigger an alert once the async method has finished executing?

This is my current implementation:

private async void SetPassword()
{
    var provider = new DpapiDataProtectionProvider("RDSupport");

    string userId = Support.Instance.GetUserIDDatabase(_currentUser);

    UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
    UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
    IdentityUser user = manager.FindById(userId);

    manager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser, string>
        (provider.Create("UserToken")) as IUserTokenProvider<IdentityUser, string>;

    string token = manager.GeneratePasswordResetToken(userId);

    manager.ResetPassword(userId, token, _newPassword);

    string hashedNewPassword = manager.PasswordHasher.HashPassword(_newPassword);                

    await userStore.SetPasswordHashAsync(user, hashedNewPassword);
    await userStore.UpdateAsync(user);

    ScriptManager.RegisterClientScriptBlock(Page, GetType(), "myalert", "alert('Password changed successfully!');", true);

    _success = true;
}

I'm currently facing an issue where the ScriptManager isn't displaying any message. Any suggestions on how to address this problem?

Answer №1

In my latest blog post, I explained how async doesn't actually alter the HTTP protocol. Once a server responds to a request, it cannot go back and send another response; that's just not how HTTP operates.

My suggestion is for your JavaScript code to make an AJAX call to this method and then trigger the alert itself when the AJAX Promise is resolved.

Answer №2

No matter how you use async and await in C#, the server will handle all execution without sending any intermediary JavaScript to the browser. The function RegisterClientScriptBlock does not execute JavaScript within the C# code itself.

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

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Using a Bookmarklet to Share Images with an Iframe

I am in the final stages of completing a bookmarklet I have been working on. I found helpful information from this stackoverflow thread. A big thank you to Treffynnon for that. So far, I have managed to fetch the title of the current page and pass it to ...

graphqlHTTP doesn't exist as a function

Check out my new GraphQL Express application below: const express = require('express'); const graphqlHTTP = require('express-graphql'); const app = express(); app.use( '/graphql', graphqlHTTP({ graphiql: true, ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Template for Kentico Article ASPX Page

Currently in the process of migrating a website from Ektron CMS to Kentico. Focused on transferring templates for articles at the moment. Seems like I may have overlooked an important detail while going through the documentation. Found this snippet in a ...

arrange a post in node.js using mongodb

My current method of ordering posts is based on the age of the user rather than the date of the post. I am working with nodejs and mongodb. router.get("/", function(req, res, next) { if (req.session._id && req.session.user) { user.getAll((err, users ...

Can a custom finish method for a subscription automatically unsubscribe itself?

Creating an Observable: public generateData(): Observable<any> { return this.fetchEndpoint() .pipe( switchMap((endpoint) => this.http.retrieve<any>(endpoint) ), take(1) ); } Subscribing to ...

Approaches to parsing two distinct JSON structures

Can I convert and assign 2 different types of JSONs like this: Type 1: { "tasks": [ { "id": "1", "task_name": "Task A", "task_status": "Pending" }, { "id": "2", "task_name": "Task B", "task_status": "Comp ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Working with DataSet object in ASP.NET

In my users table, there are two categories of users: users A and users B. On a specific page of my website, I need to display 20 users from each category based on a querystring parameter. I am considering caching this data for 6 hours since the order is n ...

Is there a way to retrieve a data value with this specific code?

I have successfully used the code below to send data to the server. However, I am now wondering how to retrieve the values of the data once the server sends back the name and surname of a person. I would like to display an alert message showing these val ...

A guide on creating visual representations of variable changes within Visual Studio

Is there a way to visually track the changes of a variable over time in Visual Studio 2010? For example, if you have the following code: double someVariable; for (int i = 0; i < 20; i++) { someVariable = Math.Pi() * i; } If you were to watch &apos ...

Exploring the use of the map function for iterating in a stepper component of

I've been attempting to integrate Redux Form into my stepper component. However, I'm facing an issue where adding form fields results in them being displayed in all three sections. To address this, I started reviewing the code for the stepper. I ...

What is the best way to access the version number of a nested array of objects while excluding one attribute or level in

I am trying to fetch a version of an object without the specific details. In other words, I want to retrieve everything except the Trades element in the nested array of objects below. What would be the most efficient way to achieve this? The list of attri ...

Tips for incorporating sessions with @html.displayfor:1. Start by setting the

I am seeking assistance on retrieving the generated ID from a view using session in MVC. @Html.Displayfor(m => m._consultation.consultid) If the value of Consultid is 1, I aim to utilize session to retrieve that ID. ...

Obtaining and storing multiple checkbox selections in a database using a JSP page

If users are required to input data on the first page, such as City, Country, and URL of the destination, and they need to select the type of destination from options like Winter, Christmas, and Summer (max 2 selections), how can these results be connected ...

Error Message: "No Source Found" in Ajax TabContainer

I am currently developing a webpage that utilizes an Ajax TabContainer to display the results of a DB2 database query. Upon encountering the error message below, I am a bit puzzled and unsure how to proceed with troubleshooting. Although I have successfull ...

Arranging a layout of interactive div elements

I am currently working on setting up a responsive grid within my HTML code. The content is contained within a bootstrap .container and consists of multiple div elements. The number of these divs can vary based on external factors, and I need the layout to ...

What is the method to designate a directory for a System.Diagnostics listener or filter within an XML file?

We have been working on a Prism application and developing some modules that are deployed in a subfolder named Modules, which are loaded by the bootstrapper. Now, we need to deploy a new listener to write traces using System.Diagnostics.Tracing. After add ...