locked
How to show message on webform (web page) while executing C# code behind RRS feed

  • Question

  • User-252566090 posted

    I am working on ASP.NET C# looping and I want to show message to the users on the completion of each loop. 

    In each round/turn of the looping, I am sending out an email message so it takes a while for each loop/round to complete and I want to display a notification message line such as "Email sent to Michael - michael@outlook.com" on the completion of each turn/round.

    I have a span element named "MessageArea" on the aspx page and the code I am using is similar to:

            int x = 1;
    
            while (x < 10)
            {
                
                // ---- Email sending code ----
    
                MessageArea.InnerHtml += "Email sent to " + RecipientName + " - " + RecipientEmailAddress;
    
                x++;
                
            }

    But, I only see the notification message when the looping completes, not at the completion of each loop/turn.
    I tried MessageArea.Update() but it looks like this only works on C#  not on ASP.NET C#

    Is there any way to display message to users while the C# code behind is running?
    Does .NET C# render the page only after the completion of the whole code block (like classic ASP)?
     

    Wednesday, March 4, 2020 6:24 AM

Answers

  • User-1330468790 posted

    Hi, ZKM128,

    Web Forms are pages that users request using their browser. When users request a page, it is compiled and executed on the server by the framework, and then the framework generates the HTML markup that the browser can render. Which means, the page will be refreshed only if a request is received by the server, like postback, and the server returns a response as HTML markup for browsers to render.

    Before providing you a solution, I would answer your question first.

    For your questions:

    • "I tried MessageArea.Update() but it looks like this only works on C#  not on ASP.NET C#"

    The area will be updated only after a postback completed so that you can only see the page refreshed with the last modification, e.g. the "MessageArea" control will only show the whole value after the while loop finished.

    • "Is there any way to display message to users while the C# code behind is running?"

    The answer is no. When the C# code behind is running, the HTML mark up will not be returned to the browser. The browser will keep the previous view until the response from server.

    Solution:

    There is a workaround to display the message during the mail sending process - using ajax call.

    The reason why you want to display the message is that the mail sending process bothers the user if the time cost can be felt. 

    If you use ajax to call "A" web method to deal with the work (static method, like webservice), you can send the email after the work is finished by calling the "B" web method.

    When a email is sent to a recipient, the message area can be placed with 

    More details, you can refer to below code.

    Script

    <script type="text/javascript">
            function updateStart() {
                var para = { data: "doing something" };
                $.ajax({
                    url: "DisplayUpdateLoop.aspx/DealBeforeSendEmail",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(para),
                    success: function (data) {
                        var persons = data.d;
                        var content = 'The pre-work is done, Start sending emails';
                        $('#' + '<%=label1.ClientID%>').html(content);
                        persons.forEach(function (item, index) {
                            callAjax(item);
                        });
                    },
                    error: function (err) {
                        alert(err);
                    }   
                })
            }
    
            function callAjax(input) {
                console.log(input);
                var sendData = { name: input.name, email: input.email };
                $.ajax({
                    url: "DisplayUpdateLoop.aspx/sendMail",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(sendData),
                    success: function (data) {
                        var mailInfo = data.d.mailInfo;
                        var content = 'Send email to ' + mailInfo.name + '[' + mailInfo.email + ']';
                        $('#' + '<%=label1.ClientID%>').html(content);
                    }
                });
            } 
        </script>

    .aspx Page:

    <div>
                <input type="button" id="updateBtn1" onclick="updateStart()" value="Start" />
                
                <br />
                <asp:HiddenField ID="hf_mailinfo" runat="server"  />
                <asp:Label ID="label1" runat="server"></asp:Label>
            </div>

    Code behind:

    protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            
            [WebMethod]
            public static List<MailInfo> DealBeforeSendEmail(string data)
            {
                //deal with stuff
                System.Threading.Thread.Sleep(2000);
    
                // return the list of people who will receive the email
                int x = 1;
                List<MailInfo> list = new List<MailInfo>();
                while (x < 10)
                {
    
                    MailInfo mailInfo = new MailInfo()
                    {
                        email = "email-" + x,
                        name = "name-" + x
                    };
                    x++;
                    list.Add(mailInfo);
                }
                
                return list;
            }
            public static Random random = new Random();
            [WebMethod]
            public static Result sendMail(string name, string email)
            {
                
                //default success
                MailInfo mailInfo = new MailInfo() { name = name, email = email };
                //Send the email
                int time = random.Next(2000,9000);
    
                System.Threading.Thread.Sleep(time);
                Result result = new Result() { mailInfo = mailInfo, sendResult = "Success" };
    
                return result;
            }
    
           
            public class Result
            {
                public MailInfo mailInfo { get; set; }
                public string sendResult { get; set; }
            }
    
           
            public class MailInfo
            {
                public string name { get; set; }
                public string email { get; set; }
            }

    Demo:

    The demo is just provide you with an idea.

    If it is not applicable for your project, you can provide more details, e.g. what you would do before sending the emails, so that we can come up with a more practical way or make modifications on above codes to integrate with your project.

    Hope this can help you.

    Best regards,

    Sean 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 5, 2020 8:48 AM

All replies

  • User-1605831695 posted

    Hi Dude,

    Cay you do one thing.. just have a string builder variable and check if the email is sent then append the text to variable.

    if all done then you can show on your message area like..

     int x = 1;
    
            StringBuilder sb = new StringBuilder();
    
            while (x < 10)
            {
    
                // ---- Email sending code ----
                if (MailSent)
                {
                    sb.AppendLine("Email sent to " + x);
    
                }
    
                x++;
            }
    
            MessageArea.InnerHtml = sb.ToString();

    Wednesday, March 4, 2020 7:01 AM
  • User-252566090 posted

    What I'm asking is, is it possible to see the notification message at the completion of each loop/turn and not when the looping completes,

    Is there any way to display message to users while the C# code behind is running (not after the completion of the c# code block)?
    Can ASP.NET C# render the page and show updated information while c# code is running?
     

    Thursday, March 5, 2020 5:51 AM
  • User-1330468790 posted

    Hi, ZKM128,

    Web Forms are pages that users request using their browser. When users request a page, it is compiled and executed on the server by the framework, and then the framework generates the HTML markup that the browser can render. Which means, the page will be refreshed only if a request is received by the server, like postback, and the server returns a response as HTML markup for browsers to render.

    Before providing you a solution, I would answer your question first.

    For your questions:

    • "I tried MessageArea.Update() but it looks like this only works on C#  not on ASP.NET C#"

    The area will be updated only after a postback completed so that you can only see the page refreshed with the last modification, e.g. the "MessageArea" control will only show the whole value after the while loop finished.

    • "Is there any way to display message to users while the C# code behind is running?"

    The answer is no. When the C# code behind is running, the HTML mark up will not be returned to the browser. The browser will keep the previous view until the response from server.

    Solution:

    There is a workaround to display the message during the mail sending process - using ajax call.

    The reason why you want to display the message is that the mail sending process bothers the user if the time cost can be felt. 

    If you use ajax to call "A" web method to deal with the work (static method, like webservice), you can send the email after the work is finished by calling the "B" web method.

    When a email is sent to a recipient, the message area can be placed with 

    More details, you can refer to below code.

    Script

    <script type="text/javascript">
            function updateStart() {
                var para = { data: "doing something" };
                $.ajax({
                    url: "DisplayUpdateLoop.aspx/DealBeforeSendEmail",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(para),
                    success: function (data) {
                        var persons = data.d;
                        var content = 'The pre-work is done, Start sending emails';
                        $('#' + '<%=label1.ClientID%>').html(content);
                        persons.forEach(function (item, index) {
                            callAjax(item);
                        });
                    },
                    error: function (err) {
                        alert(err);
                    }   
                })
            }
    
            function callAjax(input) {
                console.log(input);
                var sendData = { name: input.name, email: input.email };
                $.ajax({
                    url: "DisplayUpdateLoop.aspx/sendMail",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(sendData),
                    success: function (data) {
                        var mailInfo = data.d.mailInfo;
                        var content = 'Send email to ' + mailInfo.name + '[' + mailInfo.email + ']';
                        $('#' + '<%=label1.ClientID%>').html(content);
                    }
                });
            } 
        </script>

    .aspx Page:

    <div>
                <input type="button" id="updateBtn1" onclick="updateStart()" value="Start" />
                
                <br />
                <asp:HiddenField ID="hf_mailinfo" runat="server"  />
                <asp:Label ID="label1" runat="server"></asp:Label>
            </div>

    Code behind:

    protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            
            [WebMethod]
            public static List<MailInfo> DealBeforeSendEmail(string data)
            {
                //deal with stuff
                System.Threading.Thread.Sleep(2000);
    
                // return the list of people who will receive the email
                int x = 1;
                List<MailInfo> list = new List<MailInfo>();
                while (x < 10)
                {
    
                    MailInfo mailInfo = new MailInfo()
                    {
                        email = "email-" + x,
                        name = "name-" + x
                    };
                    x++;
                    list.Add(mailInfo);
                }
                
                return list;
            }
            public static Random random = new Random();
            [WebMethod]
            public static Result sendMail(string name, string email)
            {
                
                //default success
                MailInfo mailInfo = new MailInfo() { name = name, email = email };
                //Send the email
                int time = random.Next(2000,9000);
    
                System.Threading.Thread.Sleep(time);
                Result result = new Result() { mailInfo = mailInfo, sendResult = "Success" };
    
                return result;
            }
    
           
            public class Result
            {
                public MailInfo mailInfo { get; set; }
                public string sendResult { get; set; }
            }
    
           
            public class MailInfo
            {
                public string name { get; set; }
                public string email { get; set; }
            }

    Demo:

    The demo is just provide you with an idea.

    If it is not applicable for your project, you can provide more details, e.g. what you would do before sending the emails, so that we can come up with a more practical way or make modifications on above codes to integrate with your project.

    Hope this can help you.

    Best regards,

    Sean 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 5, 2020 8:48 AM
  • User-252566090 posted

    Thank you very much for your help, It works, I love it. 
    God bless you!

    smile

    Thursday, March 5, 2020 11:35 PM