Solved

Create a class in ASP.NET to manage Javascript confirm

Posted on 2007-11-24
14
277 Views
Last Modified: 2011-04-14
Greetings

I would like to create a class to manage using the JS Confirm. At present I have one such class for the Alert function:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for Alert
/// </summary>
public class Alert
{
    public static void Show(string message)
    {
        //
        // TODO: Add constructor logic here
        //
        string strErrorMsg = message;
        System.Text.StringBuilder sScript1 = new System.Text.StringBuilder();
        sScript1.Append("<HTML><HEAD> ");
        sScript1.Append("<script LANGUAGE='javascript'> ");
        sScript1.Append(" function MsgBox() {");
        sScript1.Append("   alert('" + strErrorMsg + "'); }  ");
        sScript1.Append("</script>");
        sScript1.Append("</HEAD>");
        sScript1.Append("<BODY onload=MsgBox();>");
        sScript1.Append("</BODY></HTML>");        
        HttpContext.Current.Response.Write(sScript1.ToString());
    }
}

What I would like to do is create something similiar for the Confirm function, that could be used with the following:

        if (Xyz.MyConfirm("My message"))
        {
          Label1.Text = "He decided to quit!";     // Confirm returns True
        }
        else
        {
        Label1.Text = "He decided to stay!";   // Confirm returns False
        }

WHAT DO I DO?
0
Comment
Question by:allanmark
  • 5
  • 5
  • 2
  • +2
14 Comments
 
LVL 63

Assisted Solution

by:Zvonko
Zvonko earned 75 total points
ID: 20344291
This cannot work:

        if (Xyz.MyConfirm("My message"))
        {
          Label1.Text = "He decided to quit!";     // Confirm returns True
        }
        else
        {
        Label1.Text = "He decided to stay!";   // Confirm returns False
        }

The reason that upper statements cannot work is that upper statement are executed on web SERVER side in one step. And first after that can some text be sent to browser to do some alert or confirm() but then it is too late to pass the confirm result to the "if" or "else" brunch because the conform JavaScript can first run after all web server parts have bin executed. You see?


0
 
LVL 27

Assisted Solution

by:Sammy
Sammy earned 100 total points
ID: 20344683
what your class should do is create a hidden field "server side" have the client script write the data "user response" to this hidden field and your object checks the value of the hidden field NOT the client response
make sense?
0
 
LVL 9

Accepted Solution

by:
codeclay earned 200 total points
ID: 20345191
Add a new method to the Alert Class .

public static void Confirm(string message)
    {
        string strErrorMsg = message;
        System.Text.StringBuilder sScript1 = new System.Text.StringBuilder();
        sScript1.Append("<HTML><HEAD> ");
        sScript1.Append("<script LANGUAGE='javascript'> ");
        sScript1.Append(" function MsgBox() {");
        sScript1.Append("   confirm('" + strErrorMsg + "'); }  ");
        sScript1.Append("</script>");
        sScript1.Append("</HEAD>");
        sScript1.Append("<BODY onload=MsgBox();>");
        sScript1.Append("</BODY></HTML>");        
        HttpContext.Current.Response.Write(sScript1.ToString());
    }

Use it just like you use the Show method.
0
 
LVL 9

Expert Comment

by:codeclay
ID: 20345196
Dont forget to change the client function name from  MsgBox()  to some thing else .. or else the Show and Confirm methods will have the same function name .
0
 
LVL 29

Assisted Solution

by:Göran Andersson
Göran Andersson earned 125 total points
ID: 20345603
You can't do that. It's not possible. A web page doesn't work that way.

Consider this:

1. The server code and the client code doesn't run at the same time.
2. The server code and the client code doesn't run in the same place.

You are trying to create something that would violate both of these.


The server code runs on the server to create the html code for the page. When the page is complete, the server code ends, and the html code is sent to the browser.

The browser recieves the html code, parses it, and displays it as a page. Here Javascript code can run inside the browser.

When the browser requests a new page from the server, the server code will be restared to create the html code for another page.

What you are trying to do is to send a response to the browser without ending the server code, then send a request back to the server and make the same instance of the server code continue where it left off with this new request. That is not possible. The http protocol doesn't work that way. The server doesn't work that way.


You have two options:

1. Send a response to the browser that contains the Javascript that shows the confirm box, and make the Javascript send a new request to the server with the information needed for you to continue the work in the new instance of the server code.

2. Use Javascript to show the confirm box before the request is even sent to the server in the first place.
0
 

Author Comment

by:allanmark
ID: 20352050
Wow! Talk about response!

Thanks to everyone for the responses!! Once again, it has been an education readign your replies!!

Two questions:

sammy1971:    What you are saying makes sense. I'd like to play around and see if I can get it working.
                        Do  you have any samples or a site when I can dig up some more on this?

codeclay:       Did and as you suggested. Now have it working.  

                      HOW DO I RETURN THE VALUE FROM THE FUNCTION AND TO WHAT DO I CHANGE
                     THE "??????????????" below??

        if ????????????????????????
        {
            TextBox1.Text = "CONFIRMED";
        }
        else
        {
            TextBox1.Text = "CANCELLED";
        }

My code:

public class ConfirmIt
{
    public static void Confirm(string message)
    {
        string strErrorMsg = message;
        System.Text.StringBuilder sScript1 = new System.Text.StringBuilder();
        sScript1.Append("<HTML><HEAD> ");
        sScript1.Append("<script LANGUAGE='javascript'> ");
        sScript1.Append(" function MessgBox() {");
        sScript1.Append("   var answer = confirm('" + strErrorMsg + "'); }  ");
        sScript1.Append("</script>");
        sScript1.Append("</HEAD>");
        sScript1.Append("<BODY onload=MessgBox();>");
        sScript1.Append("</BODY></HTML>");
        HttpContext.Current.Response.Write(sScript1.ToString());
    }
0
 
LVL 29

Assisted Solution

by:Göran Andersson
Göran Andersson earned 125 total points
ID: 20352881
> HOW DO I RETURN THE VALUE FROM THE FUNCTION

That's the part that isn't possible. When the confirm box is shown in the browser, your server code has already finished.

This is what I explained in my previous comment.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:allanmark
ID: 20353523
The penny drops!  I am beginning to understand. It's 11.55.pm (Cpae Town time) - going to call it a night and have another look in the morning!
0
 

Author Comment

by:allanmark
ID: 20355733
Greenghost -

"2. Use Javascript to show the confirm box before the request is even sent to the server in the first place."

How do I do this??
0
 
LVL 9

Expert Comment

by:codeclay
ID: 20355806
use it like this

 if ????????????????????????
        {
           Alert.Confirm("Some string");       }
        else
        {
              Alert.Confirm("Some string");
        }
And you cannot return from the function .It should be always the last statement to be executed .
0
 
LVL 9

Assisted Solution

by:codeclay
codeclay earned 200 total points
ID: 20355813
oops sorry... like this ...

ConfirmIt objConfirm = new ConfirmIt();

 if ????????????????????????
        {
            objConfirm.Confirm("Somestring");

        }
        else
        {
            objConfirm.Confirm("Somestring");

        }

 
0
 

Author Comment

by:allanmark
ID: 20356059
protected void Button4_Click(object sender, EventArgs e)
    {
        ConfirmIt objConfirm = new ConfirmIt();
       
        if (objConfirm)     // ie User clicked the ":Ok" button
        {
            TextBox1.Text = "CONFIRMED";
        }
        else
        {
            TextBox1.Text = "CANCELLED";
        }
  }

Error      1      Cannot implicitly convert type 'ConfirmIt' to 'bool'      D:\MyStuff - Allan\Training\Bug\Default2.aspx.cs      71      13      D:\...\Bug\

My thoughts:-

(1)  WIth regard to the erro above - ??? don't have a clue
(2)  I am trying to trap the return value of the function - which, as GreenGhost as explained is not
      possible.



0
 
LVL 9

Expert Comment

by:codeclay
ID: 20356125
What you are doing is totally wrong... I had already explained to you about the way ASP.NET works and where the server and client code executes .You still dont get it do you ?. As I said earlier .. it should be the last statement to be executed...
0
 

Author Comment

by:allanmark
ID: 20356174
The penny begins to drop!!!  Thanks for your patience (and to all those others who have helped!).

If I could award more points I wouild - the efforts put into helping me certainly warrant that. Will try and distribute appropriately - apologies if I offend anyone.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now