Introduction: Hello Guys, “Welcome back” Today, i am here with another one new great article. In this article I explained the implementation that how we can build a server side Yes/No confirmation box by using JavaScript in ASP.Net in C#. The JavaScript confirm function allows PostBack when OK will be clicked by the user but does nothing when Cancel will be clicked by the user and on too much conditions we need to do Server-Side operations on both OK and Cancel with click events in ASP.Net using C#.
Code for HTML Page
I will be use the following HTML controls to build a server side Yes/No confirmation box.
Button – For displaying the confirmation box.
The Button has been assigned with an OnClick and JavaScript OnClientClick event handlers.
<asp:Button ID="btnConfirm" runat="server" Text="Raise Confirm" OnClientClick="Confirm()" OnClick="OnConfirm" />
Displaying Confirmation Box using JavaScript
When the Button will be clicked by the user then Confirm JavaScript function will be called.
Inside the Confirm JavaScript function, a dynamic HTML INPUT HiddenField element is created using JavaScript. Then, JavaScript confirm function will be called and it will be response (Yes or No) is set into the Hidden Field.
Finally, the HiddenField element is added to the Form and the PostBack is occurred which triggers the OnClick event.
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
}else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
Displaying Message based on the User input in Server-Side
When the Raise Confirm button will be clicked by the user, then value of the HiddenField is fetched using Request.Form collection.
Finally, based on the HiddenFiled value an appropriate message is displayed in JavaScript Alert Message Box using RegisterStartupScript method.
Code for C# Page
protected void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
Conclusion: In above code, I have been explained implementation about implementation that how we can build a server side Yes/No confirmation box by using JavaScript in ASP.Net in C#. This code is very helpful for every developer. Bye bye and take care of yourself Developers. We will come back shortly with the new article.
Regards
Programming HUB
0 Comments