开发者

I want to show a message with 'yes' and 'no' button in ASP.net on button click if some condition is true

I want to show a message with 'yes' and 'no' button when some condition in codebehind gets true.. and if user click yes then a piece of code will execute other wise it will not.

For example:

button_click()
{
  if(condition== true)
  {
开发者_开发百科   popup a msg with yes and no
   if(user click 'yes')
   {
     then some code...
    }
  }
}


add to your code this line:

button.OnClientClick = "if (!confirm('Do you want to ...')) return false;";


Though the other answers are correct as far as how to do a dialog in Javascript, he says when some condition in codebehind gets true and then run some code (presumably also at the server). The problem seems not so much the confirm function, but how to run it conditionally.

This is going to be a little ugly if control of your app is from the server side. That is, in order to have a client interaction in the middle of two server-based operations, you will have to have two roundtrips to the server. A better way would be to have a client-sourced action that uses AJAX to get the conditions from the server, but here is how you could do it:

override void OnLoad(EventArgs e)
    {
        if (SomeCondition) {
           // cause a dialog to be displayed when page is loaded

            string confirm = @"if (confirm('Are you sure you want to continue?')) {
               __doPostBack('','1');
            }";
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), 
                Guid.NewGuid().ToString(), confirm ,true);
        }

        // check for a javascript initiated postback
        string args = Request.Form["__EVENTARGUMENT"];
        if (!String.IsNullOrEmpty(args)) {
            if (args=='1') {
                DoSomethingOnConfirm();
            }
        }
    }

Basically, you are doing two things here:

1) if SomeCondition is true (probably a post from the user) then you register a script which will be run when the page is done loading. That script causes a confirm, which, if true, causes the page to post back to itself again.

2) On that 2nd postback, the __EVENTARGUMENT (which is set by the 2nd parameter of __doPostback) will be set to 1 meaning the user clicked OK.

You'd need to add something else depending on what you want to happen if they do NOT confirm. Maybe you want to post the page again with a different argument.

Anyway - this is really a bad model and I don't recommend it. If you need client interaction based on something at the server which you don't know at the time they click a button, you should use ajax. So even as I really think this isn't a bad idea, the techniques can be useful for other legitimate purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜