简体   繁体   中英

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1) , i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.

So i was trying to accomplish it using Javascript Confirm function

var r = Confirm('Do you want to overwrite ?)

but now i have to capture this Var r into my page so that i can update my database accordingly any help how can i do it ?

On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.

Just have something like this:

<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />

If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.

Here is your code:- Add a hidden field in Net(.aspx) page

    <form id="form10" runat="server">

    <asp:HiddenField ID="hdnField" runat="server" Value="false" />
    </form>

The hidden field should be added under Form Tag.The value of this hidden field is initially "false".

Here is what you need to do in Code Behind file (.cs file)

    protected void btnSubmits_Click(object sender, EventArgs e)
    {

     if (hdnField.Value == "false")
            {

                AddJavascriptCode(itemValue); 
            }


        else if (hdnField.Value == "true")
        {

            lblMsg.Text = string.Format("You have entered {0}", itemValue);
            hdnField.Value = "false";
        }
    }

Here is the code to capture the response from OK/Confirm or Cancel button.

    private void AddJavascriptCode(string itemValue)
    {
        string script = @"<script language=""JavaScript"" type=""text/javascript"">
   window.onload=function()
  {
   var IsConfirm = 1;
   objField = document.getElementById('" + hdnField.ClientID + @"');
   objSubmit = document.getElementById('" + btnSubmit.ClientID + @"');
   IsConfirm = newConfirm('Test','You have entered " + itemValue + @" value. Do you want to overwrite ?',1,1,0);
   if(IsConfirm == true)
  {
  objField.value = 'true';
  objSubmit.click();
  }
  else
 {
  objField.value = 'false';
 }
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
    }

}

Hope this helps you :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM