(Tạo Modal Popup trong Asp.net) Trong bài viết này, thủ thuật tin học sẽ hướng dẫn các bạn cách sử dụng ASP.Net AJAX Control Toolkit ModalPopupExtender kết hợp với các thuộc tính css của bootstrap để tạo Popup trong asp.net. Cụ thể ở đây là hộp thoại Comfirm hỏi người sử dụng trước khi xóa User trong 1 danh sách.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Dưới đây là hình ảnh hộp thoại Comfirm mặc định (bên trái) và hộp thoại sau khi đã được chỉnh sửa (bên phải). Như vậy sau khi chỉnh sửa xong hộp thoại mới trông sẽ chuyên nghiệp hơn.
Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo Bảng Users có cấu trúc phía dưới trong CSDL SQL Server.

STTTên trườngKiểu trườngGhi chú
1UserIDIntTrường tự tăng
2Usernamenvarchar(100)
3FirstNamenvarchar(50)
4LastNamenvarchar(50)
5Emailnvarchar(250)
6IsDeletedbit
7CreatedOnDatedatetime
8LastModifiedOnDatedatetime


B2: Nhập dữ liệu cho bảng Users


B3: Tạo stored procedure trong SQL Server

CREATE      procedure [dbo].[Pro_Users_List]
      @IsVisible bit
as

declare @strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'Select * from Users'
set @strWhere =' where 1=1'


if @IsVisible=1
      set @strWhere= @strWhere  +' and (IsVisible=1)'

if @IsVisible=0
      set @strWhere= @strWhere  +' and (IsVisible=0 Or IsVisible Is Null)'

set @strOrder =' Order by UserName'

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL

exec sp_executesql @strSQL

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây

B4: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

Imports System.Data.SqlClient
Imports System.Data

Namespace ModalPopupConfirmBox

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString AsString

#End Region

#Region "Constructeurs"

        Public Sub New()
            Try
                _connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
                _IsError = False
            Catch ex As Exception
                _IsError = True
            End Try
        End Sub

#End Region

#Region "Proprietes"

        Public ReadOnly Property ConnectionString() AsString
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public FunctionFillTable(ByVal sql AsString) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                IfNot Para Is Nothing Then
                    For Eachp As ObjectParaIn Para
                        adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                    Next
                End If
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Object
            Try
                Dim _cnn AsNew SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd AsNew SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Eachp As ObjectParaIn Para
                    cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
                Next
                Return cmd.ExecuteScalar
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

#End Region

    End Class

    Public Class ObjectPara
        Dim _name As String
        Dim _Value As Object

        Sub New(ByVal Pname As String, ByVal PValue As Object)
            _name = Pname
            _Value = PValue
        End Sub

        Public PropertyName() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public PropertyValue() As Object
            Get
                Return _Value
            End Get
            Set(ByVal value As Object)
                _Value = value
            End Set
        End Property

    End Class

    Public Class MyEventArgs
        Inherits EventArgs

        Private Name As String
        Private MyId As String

        Public PropertySelectedName() As String
            Get
                Return Name
            End Get
            Set(ByVal value As String)
                Name = value
            End Set
        End Property

        Public Property Id() As String
            Get
                Return MyId
            End Get
            Set(ByVal value As String)
                MyId = value
            End Set
        End Property

    End Class

End Namespace

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B5: Download thư viện AjaxControlToolkit tại địa chỉ: Download

B6: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

B7: Download  thư viện Bootstrap, giải nén và copy file bootstrap.css vào thư mục Styles trong Project

B8: Tạo file Button.css trong thư mục Styles và nhập các thông tin phía dưới

.icon-yes {
    background-image: url(Images/yes.png);
    background-position: centercenter;
    height: 16px;
    width: 16px;
}

.icon-no {
    background-image: url(Images/no.png);
    background-position: centercenter;
    height: 16px;
    width: 16px;
}

B9: Tạo file GridStyle.css trong thư mục Styles và nhập các thông tin phía dưới

.GridStyle
{
    font-weight: normal;
    font-family: Arial;
    border: solid 1px #cbcbcb;
}

.GridStyle_AltRowStyle
{
    background-color: #edf5ff;
}

.GridStyle_RowStyle td, .GridStyle_AltRowStyle td
{
    padding: 4px 6px 4px 6px;
    border-color: #cbcbcb #cbcbcb #cbcbcb #cbcbcb;
    border-style: solid solid solid none;
    border-width: 1px 1px 1px medium;
}

.GridStyle_HeaderStyle th
{
    background: url(Images/sprite.png)repeat-x 0px 0px;
    border-color: #cbcbcb #cbcbcb #cbcbcb #cbcbcb;
    border-style: solid solid solid none;
    border-width: 1px 1px 1px medium;
    color: #0f5590;
    font-weight: bold;
    padding: 5px 5px 5px 5px;
    text-align: center;
    vertical-align:bottom;
    font-family:Arial;
    font-size:12px;

.GridStyle_HeaderStyle td
{
    font-family:Arial;
    font-size:12px;
    font-weight: bold;
    text-decoration: none;
    text-align: center;
    color: #0f5590;
    display: block;
    padding-right: 10px;
    vertical-align: bottom;

.GridStyle_HeaderStyle th
{
    background: url(Images/sprite.png)repeat-x 0px 0px;
    border-color: #cbcbcb #cbcbcb #cbcbcb #cbcbcb;
    border-style: solid solid solid none;
    border-width: 1px 1px 1px medium;
    color: #0f5590;
    font-weight: bold;
    padding: 5px 5px 5px 5px;
    text-align: center;
    vertical-align:bottom;
    font-family:Arial;
    font-size:12px;

.GridStyle_FooterStyle td
{
    font-family:Arial;
    font-size:13px;
    font-weight: bold;
    text-decoration: none;
    padding: 6px 6px 6px 6px;
    border-color: #cbcbcb #cbcbcb #cbcbcb #cbcbcb;
    border-style: solid solid solid none;
    border-width: 1px 1px 1px medium;
    background-color:#E0E0E0;
/* mouseover row style */

.GridStyle tr:hover{ background-color:#efefef;}


B10: Tạo thư mục UserControls và thêm file Popup_ConfirmDelete.ascx, mở file dưới dạng HTML và nhập thông tin phía dưới.

<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="Popup_ConfirmDelete.ascx.vb"Inherits="ModalPopupConfirmBox.UserControls.Popup_ConfirmDelete"%>
<%@ RegisterTagPrefix="cc1"Assembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"%>

<asp:Panel ID="pnlpopup" runat="server" style="display:none">
    <asp:UpdatePanel ID="updatePanelPopup"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button id="cmdShowPopup"runat="server"style="display:none" />
            <cc1:ModalPopupExtenderID="ModalPopupExtender_Popup"runat="server"TargetControlID="cmdShowPopup"X="750"Y="220"
                PopupControlID="pnlpopup"CancelControlID="cmdNo"BackgroundCssClass="ModalPopupBG"Drag="True"/>
                <divclass="modal"style="width:450px;">
                    <divclass="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button"id="cmdClose"runat="server"causesvalidation="false"class="close"data-dismiss="modal"aria-hidden="true">x</button>
                                <h4 class="modal-title">
                                    <asp:label id="lblHeader"runat="server"Text="Confirmation"></asp:label>
                                </h4>
                              </div>
                              <div class="modal-body">
                                   <table width="100%"cellpadding="0"cellspacing="0">
                                       <tr>
                                           <td colspan="2" align="left"style="padding:5px;">
                                               <asp:Label ID="lblMessage"CssClass="popup_Message"runat="server"Text="Do you want to delete this record?"></asp:Label>
                                           </td>
                                       </tr>
                                       <tr>
                                           <td colspan="2">
                                               <asp:Label ID="lblItemID"Visible="false"runat="server"/>
                                           </td>
                                       </tr>
                                   </table>
                              </div>
                              <div class="modal-footer">
                                   <div class="btn-group">
                                        <asp:LinkButton id="cmdYes" runat="server"CssClass="btn btn-small" CausesValidation="false">
                                            <i class="icon-yes"></i>&nbsp;&nbsp;<asp:label id="lblYes" runat="server" Text="Yes"></asp:label>
                                        </asp:LinkButton>&nbsp;
                                        <asp:LinkButton id="cmdNo" runat="server"CssClass="btn btn-small" Causesvalidation="false">
                                            <i class="icon-no"></i>&nbsp;&nbsp;<asp:label id="lblNo" runat="server" Text="No"></asp:label>
                                        </asp:LinkButton>
                                   </div>
                              </div>
                        </div>
                    </div>
                </div>
        </ContentTemplate>
    </asp:UpdatePanel>   
</asp:Panel>



B11: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục sau:

- delete.gif vào thư mục Images
- no.png, yes.png, sprite.png vào thư mục  Styles\Images

B12: Nhập Code phía dưới cho file Popup_ConfirmDelete.ascx

Namespace ModalPopupConfirmBox.UserControls
    Partial Class Popup_ConfirmDelete
        Inherits System.Web.UI.UserControl

#Region "Private Members"

        Private _ItemID As Integer
        Private _ItemName As String

#End Region

#Region "Event Click"

        Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As MyEventArgs)
        Public EventOnSelectedRow As MyEventHandler

#End Region

#Region "Private Methods"

#End Region

#Region "Pulbic Methods"

        Public Sub ShowPopup(ByVal ItemID As Integer, ByValItemName As String)
            lblItemID.Text = ItemID
            updatePanelPopup.Update()
            ModalPopupExtender_Popup.Show()
        End Sub

#End Region

#Region "Properties"

        Public PropertyItemID() As Integer
            Get
                Return _ItemID
            End Get
            Set(ByVal Value As Integer)
                _ItemID = Value
            End Set
        End Property

        Public PropertyItemName() As String
            Get
                Return _ItemName
            End Get
            Set(ByVal Value As String)
                _ItemName = Value
            End Set
        End Property

#End Region

#Region "Event Handles"

        Private SubcmdYes_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdYes.Click
            Dim MyArgs As New MyEventArgs()
            If lblItemID.Text <> ""Then
                ItemID = lblItemID.Text
            End If

            If ItemID <> -1 Then
                Dim objSQL AsNew SqlDataProvider
                objSQL.RunSQL("Pro_Users_Delete", New ObjectPara("@UserID", ItemID))
                MyArgs.Id = ItemID
                MyArgs.SelectedName = ItemName
                RaiseEvent OnSelectedRow(Me, MyArgs)
            End If
        End Sub

        Private SubcmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdNo.Click
            ModalPopupExtender_Popup.Hide()
        End Sub

        Private SubcmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdClose.ServerClick
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

    End Class


End Namespace


Với cách viết Control riêng, bạn có thể sử dụng lại ở nhiều vị trí khác nhau trong Project bằng cách nhúng nó ở những nơi cần sử dụng.

B12: Mở file Site.Master dưới dạng HTML và gắn thêm các css cho Project ngay phía dưới thẻ <link href="~/Styles/Site.css" rel="stylesheet"type="text/css"/>
<link href="~/Styles/GridStyle.css" rel="stylesheet"type="text/css"/>
<link href="~/Styles/bootstrap.css" rel="stylesheet"type="text/css"/>
<link href="~/Styles/Button.css" rel="stylesheet"type="text/css"/>

B13: Mở file Default.aspxdưới dạng HTML và  bổ xung Control

<%@ PageTitle="Confirmation box with using AJAX Modal Popup Extender in ASP.Net" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="ModalPopupConfirmBox._Default"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="Delete"Src="~/UserControls/Popup_ConfirmDelete.ascx"%>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1"runat="server">
    </asp:ScriptManager>
    <h1>
        Confirmation box with using AJAX Modal Popup Extender in ASP.Net
    </h1>
    <br />
    <ModalPopup:Delete ID="ucDeleteItem"runat="server"/>
    <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <asp:GridView ID="grvObject"runat="server"
                CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
                BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="UserID"width="100%">
                <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                <HeaderStyleCssClass="GridStyle_HeaderStyle"/>
                <RowStyleCssClass="GridStyle_RowStyle"/>
                <Columns>
                    <asp:TemplateField HeaderText="UserName">
                              <ItemStyle width="10%" />   
                        <ItemTemplate>
                            <asp:Label ID="lblUserName"Text='<%# Eval("UserName") %>' runat="server"></asp:Label>
                        </ItemTemplate>                          
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="FirstName">
                              <ItemStyle width="10%" />   
                        <ItemTemplate>
                            <asp:Label ID="lblFirstName"Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
                        </ItemTemplate>                          
                    </asp:TemplateField> 
                    <asp:TemplateField HeaderText="LastName">
                              <ItemStyle width="10%" />   
                        <ItemTemplate>
                            <asp:Label ID="lblLastName"Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
                        </ItemTemplate>                          
                    </asp:TemplateField> 
                    <asp:TemplateField HeaderText="Email">
                              <ItemStyle width="15%" />   
                        <ItemTemplate>
                            <asp:Label ID="lblEmail"Text='<%# Eval("Email") %>' runat="server"></asp:Label>
                        </ItemTemplate>                          
                    </asp:TemplateField>        
                          <asp:TemplateField HeaderText="Function">
                              <ItemStyle HorizontalAlign="Center" width="5%" /> 
                                 <ItemTemplate>
                             <asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("UserID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
                                 </ItemTemplate>
                          </asp:TemplateField>                              
                </Columns>                            
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>


B14: Viết Code cho file Default.aspx

Imports System.IO

Namespace ModalPopupConfirmBox

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private SubBindUser()
            Dim objBind As New DataTable
            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    updatePanel.Update()
                End If
            End If
        End Sub

        Private FunctionBindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Users_List", New ObjectPara("@IsDeleted", 0))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private SubgrvObject_RowDeleting(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvObject.RowDeleting
            Dim ItemID As Integer = CType(grvObject.DataKeys(e.RowIndex).Value, Integer)
            Dim ItemName As String = ""
            If ItemID <> -1 Then
                With CType(ucDeleteItem, ModalPopupConfirmBox.UserControls.Popup_ConfirmDelete)
                    .ItemID = ItemID
                    .ItemName = ItemName
                    .ShowPopup(ItemID, ItemName)
                End With
            End If
        End Sub

        Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                Dim cmdDelete AsImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
                If NotcmdDelete Is NothingThen
                    cmdDelete.ToolTip = "Delete User"
                End If
            End If
        End Sub

#End Region

#Region "Popup"

        Private SubMySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e AsModalPopupConfirmBox.MyEventArgs)
            Dim ItemName As String = ""
            With e
                If e.Id <> "" Then
                    BindUser()
                End If
            End With
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try

                AddHandler CType(ucDeleteItem, ModalPopupConfirmBox.UserControls.Popup_ConfirmDelete).OnSelectedRow, AddressOf MySelDelete_OnSelectedRow

                If Page.IsPostBack = False Then
                    BindUser()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top