现在的位置: 首页 > 综合 > 正文

Confirm message box using code behind in asp.net

2012年07月16日 ⁄ 综合 ⁄ 共 1931字 ⁄ 字号 评论关闭

经常用到js写确认框的情况,直接在前台aspx页面上写return confirm('Are you sure?') ,或者在后台code里用attributes.add()来添加以下就OK了,不过当有如下需求时:点击按钮之后执行一段代码,在该段代码中有个判断,当条件成立时询问用户是否确认提交。我们似乎不好这么做了。

那是否可以这样呢?如下:

Aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function ShowConfirmation()
{
         if(confirm("Are you want to show the value?")== true)
        {
         //Calling the server side code after confirmation from the user
          document.getElementById("btnAlelrt").click();
          }
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDetails" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnDetails" runat="server" Text="GetValue" OnClick="btnDetails_Click" />
<asp:Button ID="btnAlelrt" runat="server" Text="GetDetails" OnClick="btnAlelrt_Click" />
<br />
<br />
</div>
</form>
</body>
</html>

code部分:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//hide the button from users visibility

btnAlelrt.Style.Add("display", "none");

}

protected void btnDetails_Click(object sender, EventArgs e)

{

//here some conditions

if(txtDetails.Text == "111111")

{
Page.ClientScript.RegisterStartupScript(this.GetType(), "showAl", "ShowConfirmation();", true);

}

else

{

//do nothing!

}

}

protected void btnAlelrt_Click(object sender, EventArgs e)

{

// write your code

Page.ClientScript.RegisterStartupScript(this.GetType(), "showVal", "alert('" + txtDetails.Text + "');", true);

}

}

 

PS:小Demo一个,并非原创,自己用的时候Google来的。不知道放首页合适不^_^…(小弟新人,第二次发文,不合适留个言,我换地方!),另外请教一下,怎么才能使代码有折叠和缩进啊!!

抱歉!评论已关闭.