ASP.net - Button - Javascript Confirm dialog - exe

2019-02-23 23:09发布

I have a simple ASP.net page where users can edit information about themselves.

When "Edit" button is clicked, the form goes into edit mode and I display "Save" and "Cancel" buttons, which behave as expected.

What I want to do is this:

When "Save" is clicked, display a Javascript Confirm dialog asking the user if they want to send an email to the other users to inform them of the update just made.

If user says OK, then execute all server-side code to save the data, AND send an email. If user says Cancel, then execute all server-side code to save the data, WITHOUT sending the email.

So, I need the javascript box to set a flag which can then be read server-side, somehow... then I can do something like:

Sub btnSave_Click(sender, e) Handles btnSave.Click

    'Save all the data

    If sendEmail Then  'This flag set by reading result of javascript Confirm
        'Send the email
    End If

End Sub

I know how to add a Confirm box to the button Attributes, and have done so. I'm looking for an answer on how to read the result of that box on server side... in other words, I ALWAYS want the Page postback to happen (from clicking the button), but only SOME of the event-handler code to execute.

Hope that makes sense.

Thanks

Matt

2条回答
叼着烟拽天下
2楼-- · 2019-02-23 23:35

There are several ways to do it but I am going to use asp:HiddenField. In javascript, after user confirms, let its result to be set in the hidden field. And in server side, you can access it like any other asp.net control.

So

your aspx:

   <asp:HiddenField ID="HiddenField1" runat="server" Value="" />

CodeBehind:

  protected void Page_Load(object sender, EventArgs e)

  {

      if (!Page.IsPostBack)
      {

        var result = HiddenField1.Value; 
      } 
  }

Javascript:

 //after confirm call this
 function SetValue(val)
 {
   document.getElementById('HiddenField1').value=val;
 }
查看更多
做个烂人
3楼-- · 2019-02-23 23:52

Create a hidden field, and set the value of that field based on the result of the confirmation. You haven't shown the code/HTML for your button or form, but can you fit something like this into it:

<input type="hidden" id="sendEmail" name="sendEmail" value="" />

<input type="submit" value="Save" onclick="promptForEmail();" />

<script>
   function promptForEmail() {
      var result = Confirm("Send everybody an email?");
      // set a flag to be submitted - could be "Y"/"N" or "true"/"false"
      // or whatever suits
      document.getElementById("sendEmail").value = result ? "Y" : "N";
   }
</script>
查看更多
登录 后发表回答