CSharp: MessageBox Confirm customer rewrite

发布时间 2023-09-02 17:49:56作者: ®Geovin Du Dream Park™

js:

 

// JavaScript Document
/*
參考資源:
https://developer.mozilla.org/en-US/docs/Web/API/Window/alert
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
https://reactkungfu.com/2015/08/beautiful-confirm-window-with-react/
https://www.jquery-az.com/javascript-confirm-alert-box-fancy-and-simple-with-5-online-demos/
https://css-tricks.com/replace-javascript-dialogs-html-dialog-element/
https://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx
http://fabien-d.github.io/alertify.js/
https://sweetalert.js.org/
https://github.com/t4t5/sweetalert
https://social.msdn.microsoft.com/Forums/en-US/e19c2bda-d46b-4c47-913d-02673fa76689/confirm-message-box-yes-or-no-in-aspnet20?forum=asphtmlcssjavascript 
self.location.href;//当前页面打开URL页面
window.location.href;//当前页面打开URL页面
this.location.href;//当前页面打开URL页面
location.href;// 当前页面打开URL页面
parent.location.href;//在父页面打开新页面
top.location.href;//在顶层页面打开新页面
還有其它中文資源
*/

var alertList = [];

/**  
 * 函数说明
 * @function function(text,title,btnOkVale,btnCancelVale,golink) 重置提示框
 * @param text{String} 要提示的文本内容
 * @param title{String} 提示框的标题
 * @param btnOkVale 按钮名称
 * @param btnCancelVale 按钮名称
 * @param golink  要打开链接地址
 * @version 4.0
 * @edit geovindu 
 * @date 20230817 20230902
 * @eg confirm("程序结束!!!","网页提示","關閉","取消")
 * @eg confirm("程序结束!!!","网页提示","關閉","取消","http://www.dusystem.com")
 */
window.confirm=function(text, title = "警告", btnOkVale="確定",btnCancelVale="取消", golink,callback) {
	
	var alertMain=document.createElement('div');
	var alertBox = document.createElement('div');
	var alertTitle = document.createElement('h4');
	var alertText = document.createElement('div');
	var alertOkBtn = document.createElement('button');
	var alertbtnCancelVale = document.createElement('button');
	var alertinput=document.createElement("INPUT");
	
	
	alertinput.type = "hidden";
    alertinput.name = "confirmValue";
	alertinput.id="confirmValue";
	alertinput.className="confirmValue";
	alertinput.value="確定";
	
	alertMain.id="mainMessageBody";
	//alertMain.style.width="100%";
	//alertMain.style.height = "auto";
	//alertMain.style.display="none";
 	//alertMain.style.position="fixed";
	//alertMain.style.background="rgba(0,0,0,0)";
	//alertMain.style.top="0px";
	//alertMain.style.left="0px";
	//alertMain.style.zIndex="800";
	alertMain.className="mainMessageBody";
	//alertMain.style.textAlign="center";
	
	
	//alert弹窗整体样式
	//alertBox.style.width = "50%";
	//alertBox.style.height = "465px";//fit-content
	//alertBox.style.position = "relative";//fixed 
	//alertBox.style.marginLeft="auto";
	//alertBox.style.marginRight="auto";
	//alertBox.style.zIndex = "199";
	//alertBox.style.boxSizing="border-box";
	//alertBox.style.left = "50%";
	//alertBox.style.top = "50%";
	//alertBox.style.transform = "translate(-50% ,-50%)";
	//alertBox.style.backgroundColor = "#fff";
	//alertBox.style.padding = "10px";
	//alertBox.style.border = "2px solid #946cac";
	//alertBox.style.borderRadius = "5px";
	//alertBox.style.fontFamily = "'Courier New', Courier, monospace";
	//alertBox.style.margin="-167px 0 0 -226px";
	//alertBox.style.padding="0 15px 20px 15px";
	//alertBox.style.border="2px solid #946cac";
	alertBox.id="messageBody";
	alertBox.className="messageBody";
	//alertBox.style.display = "none";
 
	//alert 标题样式
	//alertTitle.style.padding = "0";
	//alertTitle.style.margin = "0";
	//alertTitle.style.fontWeight = "600";
	//alertTitle.style.textAlign="center";
	//alertTitle.style.borderBottom="1px solid #cda6ae";
	alertTitle.id="Messagehead";
	alertTitle.className="Messagehead";
	alertTitle.innerText = title;
	// alertTitle.innerText = "挽月阁";
 
	//内容文本样式
	//alertText.style.margin = "10px 0";
	//alertText.style.lineHeight = "1.35";
	alertText.id="MessageContent";
	alertText.className="MessageContent";
	//alertText.style.textAlign="center";
	//alertText.style.code="#946cac";
	alertText.innerText = text;
	// alertText.innerText = "落霞与孤鹜齐飞,秋水共长天一色";
 
	//ok按钮
	//alertOkBtn.style.display = "block";
	//alertOkBtn.style.width = "60px";
	//alertOkBtn.style.height = "30px";
	//alertOkBtn.style.lineHeight = "27px";
	//alertOkBtn.style.padding = "2px";
	//alertOkBtn.style.marginLeft="auto";
	//alertOkBtn.style.marginRight="auto";
	//alertOkBtn.style.float = "right";
	//alertOkBtn.style.backgroundColor = "#946cac";
	//alertOkBtn.style.border = "1px solid transparent";
	//alertOkBtn.style.borderRadius = "2px";
	//alertOkBtn.style.backgroundClip = "content-box";
	// alertOkBtn.style.transform = "scale(0.8)";
	//alertOkBtn.style.fontWeight = "600";
	//alertOkBtn.style.fontFamily = "'Courier New', Courier, monospace";
	//alertOkBtn.style.textAlign="center";
	//alertOkBtn.style.fontSize = "15px";
	//alertOkBtn.style.color="#fff";
	alertOkBtn.id="MessagebtnConfirmOk";
	alertOkBtn.className="MessagebtnConfirmOk";
	alertOkBtn.innerText = btnOkVale;
	
	
	alertbtnCancelVale.id="MessagebtnCancel";
	alertbtnCancelVale.className="MessagebtnCancel";
	alertbtnCancelVale.innerText = btnCancelVale;
	
	
	//添加ok事件
	alertOkBtn.addEventListener("click", function() {
		if(golink!=null)
		{
			alertinput.value="確定";
		  $(window).attr('location',golink);
		}
		else
		{
			alertinput.value="確定";
			console.log("確定");
             __doPostBack('UserConfirmationPostBack', 'true') //asp.net C# 给服务器传递参数
			//alert("Ok is clicked");

	     }		
			alertList.shift();
			alertMain.remove();
	
	  });
	
	//添加取消事件
	alertbtnCancelVale.addEventListener("click", function() {
		if(golink!=null)
		{
			alertinput.value="取消";
		  $(window).attr('location',golink);
		}
		else
		{
			alertinput.value="取消";
			console.log("取消");
            __doPostBack('UserConfirmationPostBack', 'false') //asp.net C#  给服务器传递参数
			//alert("Cancel is clicked");

	     }		
			alertList.shift();
			alertMain.remove();

	});
	
	//無效
	/*alertOkBtn.click=function () {
  			alert("Ok is clicked");
		};

	alertbtnCancelVale.click=function () {
  			alert("Cancel is clicked");
		};*/
	
	//添加弹窗到弹窗数组alertBox
	alertList.push(alertMain);
 
	//向页面中添加元素	注意节点父子关系
	const parent=document.body.appendChild(alertMain);
	const child=parent.appendChild(alertBox);
	child.appendChild(alertTitle);
	child.appendChild(alertText);
	child.appendChild(alertOkBtn);
	child.appendChild(alertbtnCancelVale);
	child.appendChild(alertinput);
	
};

/*
定义计时器,判断弹窗数组是否为空
确保弹窗数组中的第一个弹窗一直是显示状态
当数组为空的时候清除计时器
*/
var yue = setInterval(function() {
	if (alertList.length != 0) {
		alertList[0].style.display = "block";
	} else {
		clearInterval(yue);
	}
}, 200);

  

css:

 

#mainMessageBody{
	width: 100%;
	height: 100%;
	background: rgba(0,0,0,0);
	position: fixed;	
	top: 0;
	left: 0;
	z-index: 800;
}
#messageBody{
	width: 468px;
	height: auto;
	padding: 0px 15px 20px 15px;
	box-sizing: border-box;
	background: #fff;
	border-radius: 8px;
	position: relative;
	border: 1px solid #946cac;
	top: 50%;
	margin:auto;
}
#Messagehead{
	width: 100%;
	height: 45px;
	border-bottom: 2px solid #946cac;
	font-size: 16px;
    color: #333;
    line-height: 45px;
    text-align: center;
}
#MessageContent{
	width: 100%;
	height: auto;
	overflow: hidden;
	padding: 25px 40px 35px;
	text-align: center;
	font-size: 16px;
    color: #333;
    box-sizing: border-box;
    line-height: 28px;
}
#MessagebtnOk{
	display: block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color: #946cac;
    cursor: pointer;
    font-size: 14px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    margin: 0 auto;
    text-align: center
}
.MessagebtnConfirmOk{
	display: inline-block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color:  #946cac;
    cursor: pointer;
    font-size: 14px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    text-align: center;
    margin-left: 15%;
    margin-right: 10%;
}
.MessagebtnCancel{
	display: inline-block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color:  #946cac;
    cursor: pointer;
    font-size: 14px;
     color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    text-align: center;
    border: 1px solid transparent;
}

.ToastBox{
	width: 452px;
	height: auto;
	padding: 15px 20px;
	text-align: center;
	background: rgba(0,0,0,.5);
	color: #fff;
	font-size: 16px;
	border-radius: 8px;
	line-height: 24px;
	position: relative;
	top: 50%;
	left: 50%;
	margin: 0px 0px 0px -226px;
}
@media only  screen and (max-width: 767px) {
	#messageBody{
	width: 96%;
	height: auto;
		
	}
	
}
		
		
@media only screen and (max-width: 420px) {
.MessagebtnOk{
	display: inline-block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color:  #946cac;
    cursor: pointer;
    font-size: 14px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    text-align: center;
    margin-left: 17%;
    margin-right: 10%;
}
 }
  @media only screen and (max-width: 390px) {
.MessagebtnOk{
	display: inline-block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color:  #946cac;
    cursor: pointer;
    font-size: 14px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    text-align: center;
    margin-left: 16%;
    margin-right: 10%;
}
 }
 @media only screen and (max-width: 375px) {
.MessagebtnOk{
	display: inline-block;
    width: 100px;
    height: 34px;
    line-height: 34px;
    background-color:  #946cac;
    cursor: pointer;
    font-size: 14px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid transparent;
    text-align: center;
    margin-left: 14.5%;
    margin-right: 10%;
}
 }		

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm16.aspx.cs" Inherits="WebAppPdfDemo.WebForm16" %>

<!doctype html>
<html>
<head runat="server">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">	
<title>成长之旅 geovindu,涂聚文,Geovin Du</title>
	<meta name="Description" content="geovindu,涂聚文,Geovin Du"/>
<meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/>
<meta name="author" content="geovindu,涂聚文,Geovin Du"/>	
	 <link rel="stylesheet" href="../bootstrap/4.6.2/css/bootstrap.min.css">	
	 <script  src="../js/jquery-3.6.0.js" type="text/javascript"></script>
	<script  src="../popperjs/4.1/popper.min.js" type="text/javascript"></script>
	 <script src="../bootstrap/4.6.2/js/bootstrap.min.js" type="text/javascript"></script>	
  <script src="../ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>  
	 <script  type="text/javascript" src="../assets/js/DuSize.js"></script>
	<script type="text/javascript" src="js/Message/alert4.js"></script>
	<script type="text/javascript" src="js/Message/confirm.js"></script>

    <script type = "text/javascript">
    /*
        function __doPostBack(eventTarget, eventArgument) {

            if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

                theForm.__EVENTTARGET.value = eventTarget;

                theForm.__EVENTARGUMENT.value = eventArgument;

                theForm.submit();

            }

        }
        */
</script> 
		<script type="text/javascript">
		    function okfun() {
		        confirm('哈哈哈!!!看,没有标题網地址,我看到你了~_~', '警告', '確定', '關閉');
		    }

		     //不带网址
		    //alert("哈哈哈!!!看,没有标题網地址,看到你了~_~",'警告','確定','取消',http://www.dusystem.com/'); //带网址
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
        <!---	<div id="mainMessageBody" class="mainMessageBody" style="display: block;"><div id="messageBody" class="messageBody"><h4 id="Messagehead" class="Messagehead">警告</h4><div id="MessageContent" class="MessageContent">哈哈哈!!!看,没有标题網地址,看到你了~_~</div><button id="MessagebtnConfirmOk" class="MessagebtnConfirmOk">關閉</button><button id="MessagebtnCancel" class="MessagebtnCancel">Canle</button></div></div>
-->
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick=""/>
    </form>
</body>
</html>

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
//https://social.msdn.microsoft.com/Forums/en-US/e19c2bda-d46b-4c47-913d-02673fa76689/confirm-message-box-yes-or-no-in-aspnet20?forum=asphtmlcssjavascript
//https://www.aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx


namespace WebAppPdfDemo
{


    /// <summary>
    /// 
    /// </summary>
    public partial class WebForm16 : System.Web.UI.Page
    {


        #region Private Properties

        bool _isConfirmNeeded = true;
        string _confirmMessage = string.Empty;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets a value indicating whether this instance is confirm needed.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is confirm needed; otherwise, <c>false</c>.
        /// </value>
        public bool IsConfirmNeeded
        {
            get { return _isConfirmNeeded; }
            set { _isConfirmNeeded = value; }
        }

        /// <summary>
        /// Gets or sets the confirm message.
        /// </summary>
        /// <value>The confirm message.</value>
        public string ConfirmMessage
        {
            get { return _confirmMessage; }
            set { _confirmMessage = value; }
        }

        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //IsConfirmNeeded = true;
            //ConfirmMessage = "Do you want to proceed ?";

            //// Insure that the __doPostBack() JavaScript is added to the page...
            //ClientScript.GetPostBackEventReference(this, string.Empty);

            //if (IsPostBack)
            //{
            //    string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
            //    string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;

            //    switch (eventTarget)
            //    {
            //        case "UserConfirmationPostBack":
            //            if (Convert.ToBoolean(eventArgument))
            //            {
            //                //SaveDataInDB();
            //                Response.Write("sava");
            //            }
            //            else
            //            {
            //                Response.Write("canlce");
            //                // User said NOT to do it...
            //            }
            //            break;
            //    }
            //}

            //Set Properties
            IsConfirmNeeded = true;
            ConfirmMessage = "你真的要操作吗?";

            // Insure that the __doPostBack() JavaScript is added to the page...
            ClientScript.GetPostBackEventReference(this, string.Empty);

            if (IsPostBack)
           {
               string eventTarget = Request.Form["__EVENTTARGET"] ?? string.Empty;
                string eventArgument = Request.Form["__EVENTARGUMENT"] ?? string.Empty;
                string sss = Request["__EVENTARGUMENT"] ?? string.Empty; ;
                string confirmValue = Request.Form["confirmValue"];
                Response.Write(confirmValue);

                switch (eventTarget)
                {
                    case "UserConfirmationPostBack":
                        if (Convert.ToBoolean(eventArgument))//Convert.ToBoolean()
                        {
                            Response.Write("sava");
                            // User said to go ahead and do it...
                        }
                        else
                        {
                            Response.Write("canlce");
                            // User said NOT to do it...
                        }
                        break;
               }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (IsConfirmNeeded)
            {
                
                StringBuilder javaScript = new StringBuilder();
                string scriptKey = "ConfirmationScript";
                javaScript.AppendFormat("var userConfirmation = confirm('{0},', '警告', '確定', '關閉');", ConfirmMessage); //
                // Un-comment to only PostBack if user answers OK...
                javaScript.Append("if(userConfirmation == true )\n");
                javaScript.Append("  __doPostBack('UserConfirmationPostBack', userConfirmation);\n");
                Page.ClientScript.RegisterStartupScript(GetType(), scriptKey, javaScript.ToString(), true);
                //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "confirm('哈哈哈!!!看,没有标题網地址,我看到你了~_~', '警告', '確定', '關閉')", true);

                string confirmValue = Request.Form["confirmValue"];
                //Response.Write(confirmValue);
            }

            


        }
    }
}