skip to Main Content

Edit:
I’m doing a wide cases check on data on one button , my code is on add data button ,

  1. and same button is clicked on view page to add new data when its name is add name gets changed to save and fields emptied, and opened for editing,
  2. if user click save and all data entered correctly, data will be recorded in DB
  3. if data is not enough and user clicked save here i need the prompt if user forgot some data and want to continue he will get prompted

"entered data are not enough and will not be saved, click cancel to return to editing or okay to abort the process"

he will click cancel on prompt and return to continue adding data

  1. but if user don’t want to complete adding the new data will click okay on the message to cancel the whole process

that’s why i need to get user answer to determine by code what to do next , (1-save data ) – (2-keep recently entered data and let user continue adding) – (3-clear entered data and select the last record from db)

original:
in my asp.net page i want to make sure user has confirmed the action to be taken,
so i added a script to the master page with a function called confirm() that stores value to a hidden input,

problem:
When user interacts by pressing OK or cancel on the message it actually returns previously given value not the current value ,
if user click cancel and the previous action was OK , message returns OK not cancel

in master page:

    <script type = "text/javascript">
        function Confirm(msg) {
            var form = document.forms[0];

            // Remove the previous element added
            var oldInput = document.getElementById('myInput');
            if (oldInput !== null) form.removeChild(oldInput);

            // Add a new element
            var confirm_value = document.createElement("myInput");
            confirm_value.setAttribute('id', 'myInput');
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";

            if (confirm(msg)) {
                confirm_value.value = "Yes";
            } else {
                confirm_value.value = "No";
            }

            form.appendChild(confirm_value);
        }
    </script>

in current page.aspx.cs where user action needed, after checking empty fields and show message to user:

ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "confbkadd", "Confirm('" + "not all mandatory data where entered , click cancel to return or ok to end" + "');", true);

and then directly check the answer after the message:


string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "No")
{
confirmValue = "";
return;
}
else
{
confirmValue = "";
lblmessage.Text = "entered data where not saved";
}

2

Answers


  1. Well, I have to assume that the user is hitting some button, such as a delete, or order or whatever.

    So, a plane jane button has the ablity to do this.

    A regular button has two event stubs:

     One for the server side event
     One for the client side event
    

    And, it turns out that if the client side event returns false, then the server side button click event does not run. That’s darn near perfect as to what we need here.

    So, say this super simple markup:

        <asp:Button ID="cmdStart" runat="server" Text="Start the reactor!"
            CssClass="btn"
            OnClick="cmdStart_Click"
            OnClientClick="return myprompt()"  
            />
    
    
        <script>
            function myprompt() {
                var bolOK = confirm("Really start the Reactor?")
                return bolOK
            }
    
        </script>
    

    So, note how the button has 2 events. (server and client).

    If client click event returns false, then server button/code does not run.
    (we return false for the JavaScript code).

    thus, above looks like this:

    enter image description here

    If you hit ok, then server button runs.

    so, no mess of some hidden controls etc. is required here.

    Do keep in mind that if in place of those "VERY ugly" built in browser dialogs, you might want to adopt say sweet alert, or say even a jQuery.UI dialog.

    such dialogs (and near ALL JavaScript) code today is NOT supposed to use blocking code. The only 2 features left in a browser that allows this is alter(), and confirm(). And in the future, they may well be removed due that blocking and ability to freeze up a browswer.

    However, a cute/cool trick can be used for such asyncrious dialogs.

    So, say we want to do the same with a jQuery.UI dialog.

    Now, of course I might create a system wide dialog pop
    (or, hey, even better how about a user control we just drop into any page).

    so in above, when you click on the button, then the client side code runs, pops the dialog AND THEN RETURNS false!!!!

    When the user hits "ok", then we set the mydelpromptok = true AND THEN click the SAME button again!!!

    Now the button click runs the client side, it NOW returns true, and then the server side code runs.

    jQuery.UI must be added to your project, assuming we already have jQuery.

    And I VERY much like the jQuery.UI dialogs, since you can position them where the user clicked.

    The dialog part requires you have a "div" in the page.

    So, say this markup:

        <asp:Button ID="cmdDelete" runat="server" Text="Delete Record"  CssClass="btn"
            OnClick="cmdDelete_Click"  
            OnClientClick="return mydelprompt2(this)" />
    
        <div id="mydeldiv" style="display:none">
            <img src="../Content/Rhotel.jpg" style="float:left" />
            <h4><i>Delete this Hotel, are you sure?</i></h4>
        </div>
    
        <script>
            mydelpromptok = false
            function mydelprompt2(btn) {
                if (mydelpromptok) {
                    mydelpromptok = false
                    return true
                }
    
                var mydiv = $("#mydeldiv")
                mydiv.dialog({
                    modal: true, appendTo: "form",
                    title: "Delete Hotel?", closeText: "",
                    width: "20%",
                    position: { my: 'left top', at: 'right bottom', of: btn },
                    dialogClass: "dialogWithDropShadow",
                    buttons: {
                        Ok: (function () {
                            mydiv.dialog("close")
                            mydelpromptok = true
                            btn.click()
                        }),
                        Cancel: (function () {
                            mydiv.dialog("close")
                        })
                    }
                });
                return false;
            }
        </script>
    

    And the result is now this:

    enter image description here

    so, you don’t need all that hidden stuff you are attempting here.

    You can EVEN put the client side confirm RIGHT into the button if you in a hurry, and don’t have time for some fancy pants dialog like the 2nd example above.

    so, you can/could do this:

        <asp:Button ID="cmdStart" runat="server" Text="Start the reactor!"
            CssClass="btn"
            OnClick="cmdStart_Click"
            OnClientClick="return confirm('Really do this?')"  
            />
    

    So, we don’t even need to call a client side js routine, we just put the js expression right into the above button.

    Edit: so a proof of concept how this works

    So, at the end of the day, it really does not matter how/when/where/what point in the code + ui we arrived.

    The GOAL here is this:

    I have a save button, and I want a dialog to run that simple plane jane asp.net button, or not. Really kind of simple.

    And 1/2 dozen scenarios as to some verify or some "conditional" code to allow or not allow that save button to run is STILL THE SAME goal.

    Lets take the following example:

    enter image description here

    so, in above, we have ONE simple plain jane save button:

    This one:

    enter image description here

    So, if you click on save, we run that SIMPLE button click code beind.

    Not all that imporant, but the code for that click button to save the current reocrd we are editing was this:

    protected void cmdSave_Click(object sender, EventArgs e)
    {
        int PKID = (int)ViewState["PKID"];
        General.FWriter(this.EditRecord, PKID, "tblHotelsA");
        LoadData();  // re-load grid to show any changes
    }
    

    (I wrote some general code to edit ANY form – as it makes VERY little sense to write over and over the same kind of code to save a simple reocrd).

    Now, lets say we want to add some verification to that save button.

    Say, you must enter Last Name, and you must enter City.

    So, if you click on save, we NOW do not want that code behind to run.

    So, as per the previous examples?

    Then all we do is make sure we return FALSE from the client side js code and the save button will not run. REALLY very simple.

    So, not clear that anything more then this VERY simple concept is required here.

    So, here is that plain jane button
    (actually, I used a link button — only reason is they can display bootstrap icons).

    so, the button code is this:

        <asp:LinkButton id="cmdSave" runat="server" class="btn myshadow"
            OnClick="cmdSave_Click"
    
            <span aria-hidden="true" class="glyphicon glyphicon-floppy-saved">Save</span>
        </asp:LinkButton>
    

    So,now lets add that trick/tip of a client side routine for that button click.

    So, we now have this:

        <asp:LinkButton id="cmdSave" runat="server" class="btn myshadow"
            OnClick="cmdSave_Click"
            OnClientClick="return myverify()" >
            <span aria-hidden="true" class="glyphicon glyphicon-floppy-saved">Save</span>
        </asp:LinkButton>
    

    so, our client side js code now can "test" "check" verify if the user has entered all the fields we want.

    If not, then we pop a dialog – tell the user, and AGAIN thus don’t return true value. (return true = run that server side click event – in this case the save code).

    So, as noted, lets test for LastName, and city – they have to be entered.

    So, our code can be this:

    the 2 button events are:

            OnClick="cmdSave_Click"
            OnClientClick="return myverify(this)" >
    

    So, now

    <script>
    
        myverifyok = false
        function myverify(btn) {
            if (myverifyok) {
                myverifyok = false  // not really required unless no post-back
                return true
            }
            if ( $('#tLN').val() == "") {
                popmessage(btn,"Please enter a value for last Name")
                return false
            }
            if ( $('#tCity').val() == "") {
                popmessage(btn,"Please enter a value for City")
                return false
            }
    
            // get here, and we verifed
            myverifyok = true
            btn.click()
    
        }
    

    again we return true (server button runs), false it does not.

    However, since I using a jQuery.UI dialog, (and not alert() or confirm(), then the code does not halt, so I have to use that flag trick, and click the button again.

    The pop message routine is this:

        function popmessage(btn, sMessage) {
            $('#reqfield').text(sMessage)
            var mydiv = $('#drequired')
            mydiv.dialog({
                modal: true, appendTo: "form",
                title: "Required field missing", closeText: "",
                width: "350px",
                position: { my: 'left bottom', at: 'right top', of: btn },
                dialogClass: "dialogWithDropShadow",
                buttons: {
                    ' ok ': function () {
                        mydiv.dialog('close')
                    }
                }
            });
            return false
    

    And our div for the pop up is this:

        <div id="drequired" style="display:none">
            <h4 id="reqfield"></h4>
        </div>
    

    So, the result looks like this:

    enter image description here

    and same button is clicked on view page to add new data when its name is add name gets changed to save

    do you REALLY want to start changing what a button does?

    why not just have Save, Cancel, and delete.

    That way the UI is 100% the same to the user.

    If you want to "add", then have a add button like this:

    enter image description here

    That way, your code to add, or edit is 100% the same
    (well, a tiny check for no PK id when you hit save, and there is no existing record).

    So, at the end of the day?

    we did a 0 or 1 in regards to the ONE simple save button.

    Either true passed back, and that button code behind runs, or it does not.

    As pointed out, it probably better to use some required field validators, but the proof of concpet above can still be used for other types of critera.

    Once you have this proof of concept working?

    Then add a "general" routine into the master page, with some nice parameter’s and options and then you can with great ease have a dialog confirmation for any save button you have. But, baby steps here, baby steps.

    Login or Signup to reply.
  2. i would use RequiredFieldValidator from toolbox so when texts are enabled and not filled with data , validator will halt execution , and to cancel entering data you just need to refresh

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search