.Net自定義後臺可用的提示(alert,confirm)控件

從不會到會,這是一個累而充實的過程;從會到精,這是一個有收穫的過程;從精到簡化,到自動化,這是一個普普通通的過程。但這只是一個短暫的過程,他有盡頭,有終點。
一份可以讓我爲之貢獻一生的事業應該是——可以讓我不斷追求完美,追求高效率,逐漸簡化,然後實現自動化。換言之就是太懶,需要用不斷學習新東西,打發時間,以維持生存。

言歸正傳,之前寫了一篇文章:用js和css重寫alert和Confirm提示窗口,支持服務器控件調用。主要是供前端代碼調用,這篇文章寫通過建立後臺控件來實現前臺的alert和confirm提示窗口。即後臺直接使用alert和confirm方法後,在頁面加載完後會自動彈出提示框。
先上調用頁面.aspx的前臺代碼

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

<%@ Register TagPrefix="Promt" TagName="PromtLayer" Src="~/Controls/PromptLayer1.ascx" %>

<!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></title>
    <script src="js/jquery-1.12.1.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <Promt:PromtLayer ID="ucPromtLayer" runat="server"></Promt:PromtLayer>
    <div>
        test alert control
    </div>
    <div>
        <asp:Button ID="btnConfirm" runat="server" Text="test Confirm" onclick="btnConfirm_Click"/>
    </div>
     <div>
        <asp:Button ID="btnAlert" runat="server" Text="test Alert" 
             onclick="btnAlert_Click" />
    </div>
    </form>

</body>
</html>

其中<Promt:PromtLayer ID="ucPromtLayer" runat="server"></Promt:PromtLayer>是控件的調用代碼,記得添加頭部的引用。
調用頁面的後臺.cs代碼:

using System;

namespace WebApplication1
{
    public partial class InfoPromptLayer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btnConfirm.OnClientClick = ucPromtLayer.ConfirmForClientClick("提示消息", "是否確認刪除!", 240, 200, btnConfirm.ClientID);
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            string callback = @"function (r) 
                                {
                                    if (r) 
                                    {
                                       PlusAlert('模擬Alert彈窗', '你單擊了確定');    
                                    } 
                                    else 
                                    {
                                        PlusAlert('模擬Alert彈窗', '你單擊了取消');
                                    }
                                }";
            ucPromtLayer.Confirm("test title", "test message", 240, 200, callback);
        }
        protected void btnAlert_Click(object sender, EventArgs e)
        {
            string callback = @"function (r) 
                                {
                                    if (r) 
                                    {
                                       PlusAlert('模擬Alert彈窗', '你單擊了確定');    
                                    } 
                                    else 
                                    {
                                        PlusAlert('模擬Alert彈窗', '你單擊了取消');
                                    }
                                }";
            ucPromtLayer.Alert("test title", "test message", 240, 200, callback);
        }

    }
}

這裏定義了兩個.net的前臺按鈕的單擊事件,頁面加載時還給按鈕添加了OnClientClick事件,這在很多表格的事件綁定上用到。callback這個參數是用js寫的一個回調方法。
接下來是控件的前臺.ascx代碼:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PromptLayer1.ascx.cs" Inherits="WebApplication1.Controls.PromptLayer1" %>
<script src="<%=HttpRoot%>/js/promotLayer.js" type="text/javascript"></script>

其中HttpRoot變量主要是用於獲取js路徑用
控件後臺.cs代碼:

using System;
using System.Web.UI;

namespace WebApplication1.Controls
{
    public partial class PromptLayer1 : System.Web.UI.UserControl
    {
        public string HttpRoot
        {
            get
            {
                return Request.ApplicationPath;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 後臺alert
        /// </summary>
        /// <param name="str_title"></param>
        /// <param name="str_message"></param>
        /// <param name="str_width"></param>
        /// <param name="str_height"></param>
        /// <param name="str_callback">完整的前臺js返回函數的字符串</param>
        public void Alert(string str_title, string str_message, int str_width, int str_height, string str_callback) {
            string strScript = "PlusAlert('" + str_title + "', '" + str_message + "', " + str_width + "," + str_height + "," + str_callback + ")";
            strScript = "<script type=\"text/javascript\">\n" + strScript + "\n</script>";
            Page.ClientScript.RegisterStartupScript(GetType(),"alert",strScript);
        }
        /// <summary>
        /// 後臺Confirm
        /// </summary>
        /// <param name="str_title"></param>
        /// <param name="str_message"></param>
        /// <param name="str_width"></param>
        /// <param name="str_height"></param>
        /// <param name="str_callback">完整的前臺js返回函數的字符串</param>
        public void Confirm(string str_title, string str_message, int str_width, int str_height, string str_callback)
        {
            string strScript = "PlusConfirm('" + str_title + "', '" + str_message + "', " + str_width + "," + str_height + "," + str_callback + ")";
            strScript = "<script type=\"text/javascript\">\n" + strScript + "\n</script>";
            Page.ClientScript.RegisterStartupScript(GetType(), "alert", strScript);
        }
        /// <summary>
        /// 後臺控件標籤內直接添加confirm
        /// </summary>
        /// <param name="str_title"></param>
        /// <param name="str_message"></param>
        /// <param name="str_width"></param>
        /// <param name="str_height"></param>
        /// <param name="controlId">使用onClientClick事件的控件id</param>
        public string ConfirmForClientClick(string str_title, string str_message, int str_width, int str_height, string controlId)
        {
            string strScript = "return ConfirmForClientClick('" + str_title + "', '" + str_message + "', " + str_width + "," + str_height + ",'" + controlId + "')";
            return strScript;
        }
    }
}

最後是提示窗體的實際生成代碼:

//後臺控件調用自定義confirm窗口時,需要單擊控件後先返回false,當點擊確定時,再次模擬點擊控件。
var IsOk = false;
function ConfirmForClientClick(title, message, width, height, controlId) {
    if (IsOk) {
        return true;
    }
    PlusConfirm(title, message, width, height, function (r) {
        if (r) {
            IsOk = true;
            document.getElementById(controlId).click();
        } else {
            IsOk = false;
        }
    });
    return false;
}
//css樣式
var strStyle = "<style type='text/css'>";
strStyle += ".confirmPop{width:350px; height:170px;border:#64a64b solid 1px; position:absolute;background:#fff;z-index: 9999;left: 0px;right: 0px;top: 0px; bottom: 0px;margin:auto;font-family:Microsoft Yahei;}";
strStyle += ".confirmTitle{ background-color:#69ae4e; position:relative;}";
strStyle += ".confirmTitle span{line-height: 30px;margin-left: 6px;font-size: 13px;color: white;}";
strStyle += ".confirmTitle .btnclose{float: right;font-size: 19px;color: rgba(255, 255, 255, 0.88);height: 30px;width: 30px;cursor: pointer;text-align: center;}";
strStyle += ".confirmText{ margin:30px 40px;text-align: center;}.confirmText span{ font-size: 15px;}";
strStyle += ".confirmBtnBox{ text-align:center; margin:30px 0 28px 0;font-size: 15px;}";
strStyle += ".confirmBtnBox .btn{ display:inline-block; padding:0 25px; height:30px; line-height:30px; color:#fff; background-color: #64a64b;margin: 0 10px;}";
strStyle += ".confirmBtnBox .btn:hover{ background-color:#509236;}";
strStyle += ".confirmGlobal{display: block; position: fixed; clear: both; z-index: 9999; left: 0px; top: 0px; bottom: 0px;border: 0px solid rgb(255, 255, 255); width: 100%; height: 100%; opacity: 0.5; background: rgb(255, 255, 255);}";
strStyle += "</style>";
$("head").append(strStyle)
//js事件
$.alerts = {
    alert: function (title, message, width, height, callback) {
        if (title == null) title = 'Alert';
        $.alerts._show(title, message, width, height, 'alert', callback);
    },
    confirm: function (title, message, width, height, callback) {
        if (title == null) { title = 'Confirm'; }
        return $.alerts._show(title, message, width, height, 'confirm', callback);
    },
    _show: function (title, msg, width, height, type, callback) {
        renderHtml(title, msg, width, height, type);
        switch (type) {
            case 'alert':
                $("#confirmBtnSure").click(function () {
                    $.alerts._hide();
                    if (callback) {
                        callback(true);
                    }
                });
                $("#confirmBtnSure").focus().keypress(function (e) {
                    if (e.keyCode == 13 || e.keyCode == 27) {
                        $("#confirmBtnSure").trigger('click');
                    }
                });
                break;
            case 'confirm':
                $("#confirmBtnSure").click(function () {
                    $.alerts._hide();
                    if (callback) {
                        return callback(true);
                    }
                });
                $("#confirmBtnCancel").click(function () {
                    $.alerts._hide();
                    if (callback) {
                        return callback(false);
                    }
                });
                $("#confirmBtnCancel").focus();
                $("#confirmBtnSure, #confirmBtnCancel").keypress(function (e) {
                    if (e.keyCode == 13) {//回車
                        $("#confirmBtnSure").trigger('click');
                    }
                    if (e.keyCode == 27) {//ESC
                        $("#confirmBtnCancel").trigger('click');
                    }
                });
                break;
        }
    },
    _hide: function () {
        $("#confirmId,#confirmGlobal").remove();
    }
}
//修改Alert彈層提示框
//標題-title,提示信息-altInfo,確認按鈕函數-callback,寬度-width
PlusAlert = function (title, message, width, height, callback) {
    $.alerts.alert(title, message, width, height, callback);
}
//修改Confirm彈層提示框
PlusConfirm = function (title, message, width, height, callback) {
    $.alerts.confirm(title, message, width, height, callback);
};
//生成html並渲染樣式
function renderHtml(title, msg, width, height, type) {
    var strPrompt = "<div id='confirmId' style='";
    if (width) {
        strPrompt += "width: " + width + "px;";
    }
    if (height) {
        strPrompt += "height: " + height + "px;";
    }
    strPrompt += "'>";
    strPrompt += "<div id='confirmTitleDiv'><span id='confirmTitle'>" + title + "</span><a class='btnclose'>X</a></div><div id='confirmTextDiv'><span id='confirmInfo'>";
    strPrompt += msg + "</span></div><div id='confirmBtnBox'>";
    strPrompt += "<a class='btn' href='javascript:void(0)' id='confirmBtnSure'>確 認</a>";
    if (type == "confirm") {
        strPrompt += "<a class='btn' href='javascript:void(0)' id='confirmBtnCancel'>取 消</a>";
    }
    strPrompt += "</div></div>";
    $("body").append(strPrompt)
    //遮罩層
    $("#confirmId").before("<div id='confirmGlobal'></div>")
    //手動渲染樣式
    $("#confirmId").attr("class", "confirmPop");
    $("#confirmTitleDiv").attr("class", "confirmTitle");
    $("#confirmTextDiv").attr("class", "confirmText");
    $("#confirmBtnBox").attr("class", "confirmBtnBox");
    $("#confirmBtnSure").attr("class", "btn");
    $("#confirmBtnCancel").attr("class", "btn");
    $("#confirmGlobal").attr("class", "confirmGlobal");
    $(".btnclose").click(function () {
        $.alerts._hide();
    });
}

寫代碼的時候養成一個習慣,再簡單的代碼能加註釋就加註釋。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章