.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();
    });
}

写代码的时候养成一个习惯,再简单的代码能加注释就加注释。

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