Thêm, sửa, xóa dữ liệu sử dụng AJAX Modal Popup Extender trong ASP.Net
(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. Popup này sẽ có chức năng thêm, sửa dữ liệu một cách nhanh chóng, thuận tiện và dễ dàng. Sau khi thực hiện xong các thao tác thêm, sửa dữ liệu sẽ được hiển thị ngay tức thì lên Gridview.
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Accounts có cấu trúc phía dưới- B1: Tạo CSDL Customers trong SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | AccountID | Int | Trường tự tăng |
2 | AccountCode | nvarchar(25) | |
3 | AccName | nvarchar(250) | |
4 | AccAddress | nvarchar(250) | |
5 | AccPhone | nvarchar(50) | |
6 | AccFAX | nvarchar(50) | |
7 | AccEmail | nvarchar(50) | |
8 | AccWebsite | nvarchar(150) | |
9 | AccDesc | nvarchar(1500) | |
10 | CreatedDate | datetime | |
11 | ModifiedDate | datetime |
- B3: Nhập dữ liệu cho bảng Accounts
- B4: Tạo các stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Accounts_Add]
@AccountCode nvarchar(25)
,@AccName nvarchar(250)
,@AccAddress nvarchar(250)
,@AccPhone nvarchar(80)
,@AccFAX nvarchar(50)
,@AccEmail nvarchar(500)
,@AccWebsite nvarchar(150)
,@AccDesc nvarchar(2000)
AS
INSERT INTO Accounts (
[AccountCode]
,[AccName]
,[AccAddress]
,[AccPhone]
,[AccFAX]
,[AccEmail]
,[AccWebsite]
,[AccDesc]
,[CreatedDate]
,[ModifiedDate]
) VALUES (
@AccountCode
,@AccName
,@AccAddress
,@AccPhone
,@AccFAX
,@AccEmail
,@AccWebsite
,@AccDesc
,getdate()
,getdate()
)
select SCOPE_IDENTITY()
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_Delete]
@AccountID int
AS
DELETE FROM Accounts
WHERE
[AccountID] = @AccountID
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_Get]
@AccountID int
AS
SELECT * FROM Accounts
WHERE
AccountID = @AccountID
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_List]
@Keyword nvarchar(250),
@SortField nvarchar(50),
@SortType nvarchar(10)
AS
declare
@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Accounts'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (AccountCode like
N''%' +@Keyword+'%''
Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'
if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by AccName'
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_Update]
@AccountID int,
@AccountCode nvarchar(25),
@AccName nvarchar(250),
@AccAddress nvarchar(250),
@AccPhone nvarchar(80),
@AccFAX nvarchar(50),
@AccEmail nvarchar(500),
@AccWebsite nvarchar(150),
@AccDesc nvarchar(2000)
AS
UPDATE Accounts SET
[AccountCode] =
@AccountCode
,[AccName] = @AccName
,[AccAddress]
= @AccAddress
,[AccPhone] = @AccPhone
,[AccFAX] = @AccFAX
,[AccEmail] = @AccEmail
,[AccWebsite]
= @AccWebsite
,[AccDesc] = @AccDesc
,[ModifiedDate]
= getdate()
WHERE
[AccountID] =
@AccountID
Go
- B5: 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 AddEditRecordsUsingModalPopup
Public Class SqlDataProvider
#Region "Membres
Prives"
Shared _IsError As Boolean = False
Private _connectionString As
String
#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() As
String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function
FillTable(ByVal sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
FillTable(ByVal ProcName As String, ByVal ParamArray
Para() As ObjectPara)
As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If Not
Para Is Nothing
Then
For Each
p As ObjectPara
In 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 Function
RunSQL(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn As
New SqlConnection(_connectionString)
_cnn.Open()
Dim cmd As
New SqlCommand(ProcName,
_cnn)
cmd.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
GetRow(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
adap.Fill(tb)
If tb.Rows.Count Then
Return tb.Rows(0)
End If
Catch ex As Exception
Return Nothing
End Try
Return Nothing
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 Property
Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property
Value() 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 Property SelectedName()
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
- B6: Download thư viện AjaxControlToolkit tại địa chỉ: Download
- B7: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.
- B8: Download thư viện Bootstrap, giải nén và copy file bootstrap.css vào thư mục Styles trong Project
- B9: Tạo file Button.css trong thư mục Styles và nhập các thông tin phía dưới
.icon-add {
background-image: url(Images/add.gif);
background-position: center
center;
height: 16px;
width: 16px;
}
.icon-update {
background-image: url(Images/save.gif);
background-position: center
center;
height: 16px;
width: 16px;
}
.icon-close {
background-image: url(Images/lt.gif);
background-position: center
center;
height: 16px;
width: 16px;
}
.icon-yes {
background-image: url(Images/yes.png);
background-position: center
center;
height: 16px;
width: 16px;
}
.icon-no {
background-image: url(Images/no.png);
background-position: center
center;
height: 16px;
width: 16px;
}
- B10: 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;}
- B11: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục sau:
+ edit.gif, delete.gif, icon_search.gif vào thư mục Images
+ no.png, yes.png, sprite.png vào thư mục Styles\Images
- B12: 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.
<%@ Control
Language="vb"
AutoEventWireup="false"
CodeBehind="Popup_ConfirmDelete.ascx.vb"
Inherits="AddEditRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete"
%>
<%@ Register
TagPrefix="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:ModalPopupExtender
ID="ModalPopupExtender_Popup"
runat="server"
TargetControlID="cmdShowPopup"
X="750"
Y="220"
PopupControlID="pnlpopup"
CancelControlID="cmdNo"
BackgroundCssClass="ModalPopupBG"
Drag="True"
/>
<div
class="modal"
style="width:450px;">
<div
class="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> <asp:label id="lblYes" runat="server" Text="Yes"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdNo" runat="server"
CssClass="btn
btn-small" Causesvalidation="false">
<i class="icon-no"></i> <asp:label id="lblNo" runat="server" Text="No"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel> - B13: Nhập Code phía dưới cho file Popup_ConfirmDelete.ascx
Namespace AddEditRecordsUsingModalPopup.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 Event
OnSelectedRow As MyEventHandler
#End Region
#Region "Private
Methods"
#End Region
#Region "Pulbic
Methods"
Public Sub ShowPopup(ByVal ItemID As Integer, ByVal
ItemName As String)
lblItemID.Text = ItemID
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Properties"
Public Property
ItemID() As Integer
Get
Return _ItemID
End Get
Set(ByVal Value As Integer)
_ItemID = Value
End Set
End Property
Public Property
ItemName() As String
Get
Return _ItemName
End Get
Set(ByVal Value As String)
_ItemName = Value
End Set
End Property
#End Region
#Region "Event
Handles"
Private Sub cmdYes_Click(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles
cmdYes.Click
Dim MyArgs As New MyEventArgs()
If lblItemID.Text <> ""
Then
ItemID = lblItemID.Text
End If
If ItemID <> -1 Then
Dim objSQL As
New SqlDataProvider
objSQL.RunSQL("Pro_Accounts_Delete",
New ObjectPara("@AccountID", ItemID))
MyArgs.Id = ItemID
MyArgs.SelectedName = ItemName
RaiseEvent OnSelectedRow(Me, MyArgs)
End If
End Sub
Private Sub
cmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdNo.Click
ModalPopupExtender_Popup.Hide()
End Sub
Private Sub
cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClose.ServerClick
ModalPopupExtender_Popup.Hide()
End Sub
#End Region
End Class
End Namespace
<%@ Control
Language="vb"
AutoEventWireup="false"
CodeBehind="Popup_EditRecord.ascx.vb"
Inherits="AddEditRecordsUsingModalPopup.UserControls.Popup_EditRecord"
%>
<%@ Register
TagPrefix="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:ModalPopupExtender
ID="ModalPopupExtender_Popup"
runat="server"
TargetControlID="cmdShowPopup"
X="620"
Y="150"
PopupControlID="pnlpopup"
CancelControlID="cmdCancel"
BackgroundCssClass="ModalPopupBG"
Drag="True"
/>
<div
class="modal"
style="width:700px;">
<div
class="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"></asp:label>
</h4>
</div>
<div class="modal-body">
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td colspan="4" align="left" style="padding:2px;">
<asp:Label ID="lblMessage"
CssClass="popup_Message"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="4">
<asp:Label ID="lblItemID"
Visible="false"
runat="server"/>
</td>
</tr>
<tr>
<td>
<asp:label id="plAccountCode"
runat="server"
CssClass="CRM_Label"
Text="Account Code
(*)"></asp:label>
</td>
<td colspan="3">
<asp:TextBox ID="txtAccCode"
CssClass="form-control"
runat="server"
Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valAccountCode"
runat="server"
ControlToValidate="txtAccCode"
Display="dynamic"
ErrorMessage="Enter
Account Code"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccName" runat="server" CssClass="CRM_Label" Text="Account Name (*)"></asp:Label>
</td>
<td colspan="3">
<asp:TextBox ID="txtAccName"
CssClass="form-control"
runat="server"
width="516px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valAccName"
runat="server"
ControlToValidate="txtAccName"
Display="dynamic"
ErrorMessage="Enter
Account Name"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccAddress"
runat="server"
CssClass="CRM_Label"
Text="Address"></asp:Label>
</td>
<td colspan="3">
<asp:TextBox ID="txtAccAddress"
CssClass="form-control"
TextMode="multiLine"
runat="server"
Height="45px"
width="516px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width:48%;">
<asp:Label ID="plPhone"
runat="server"
CssClass="CRM_Label"
Text="Phone"></asp:Label>
</td>
<td style="width:40%;">
<asp:TextBox ID="txtAccPhone"
CssClass="form-control"
runat="server"
width="220px"></asp:TextBox>
</td>
<td style="width:10%;">
<asp:Label ID="plAccFax"
runat="server"
CssClass="CRM_Label"
Text="Fax"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtAccFax"
CssClass="form-control"
runat="server"
width="220px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccEmail"
runat="server"
CssClass="CRM_Label"
Text="Email"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtAccEmail"
CssClass="form-control"
runat="server"
width="220px"></asp:TextBox>
<asp:regularexpressionvalidator
id="cvEmail"
runat="server"
ErrorMessage="Error
Email" CssClass="Normal" ControlToValidate="txtAccEmail" Display="Dynamic" ValidationExpression="[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+"></asp:regularexpressionvalidator>
</td>
<td>
<asp:Label ID="plWebsite"
runat="server"
CssClass="CRM_Label"
Text="Website"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtAccWebsite"
CssClass="form-control"
runat="server"
width="220px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plDescription"
runat="server"
CssClass="CRM_Label"
Text="Description"></asp:Label>
</td>
<td colspan="3">
<asp:textbox id="txtDescription"
CssClass="form-control"
runat="server"
textmode="multiline"
width="516px"
Height="45px"></asp:textbox>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdAdd" runat="server"
CssClass="btn
btn-small" CausesValidation="true">
<i class="icon-add"></i> <asp:label id="lblAdd" runat="server" Text="Save & Add"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdUpdate"
runat="server"
CssClass="btn
btn-small" CausesValidation="true">
<i class="icon-update"></i> <asp:label id="lblUpdate" runat="server" Text="Save"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdCancel"
runat="server"
CssClass="btn
btn-small" Causesvalidation="false">
<i class="icon-close"></i> <asp:label id="lblClose" runat="server" Text="Close"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>- B15: Nhập Code phía dưới cho file Popup_EditRecord.ascx
Namespace AddEditRecordsUsingModalPopup.UserControls
Partial Class Popup_EditRecord
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 Event
OnSelectedRow As MyEventHandler
#End Region
#Region "Private
Methods"
Private Sub
SetTitle()
If lblItemID.Text <> ""
And lblItemID.Text <> "-1" Then
lblHeader.Text = "Edit Record"
Else
lblHeader.Text = "Add Record"
End If
End Sub
Private Sub
ResetControls()
lblItemID.Text = ""
txtAccCode.Text = ""
txtAccName.Text = ""
txtAccAddress.Text = ""
txtAccPhone.Text = ""
txtAccFax.Text = ""
txtAccEmail.Text = ""
txtAccWebsite.Text = ""
txtDescription.Text = ""
End Sub
#End Region
#Region "Pulbic
Methods"
Public Sub ShowPopup(ByVal ItemID As Integer)
lblItemID.Text = ItemID
SetTitle()
GetInfo(ItemID)
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Data
Methods"
Private Function
UpdateRecord() As Integer
Dim objSQL As New SqlDataProvider
Dim ItemID As Integer = -1
'Edit Record
If lblItemID.Text <> ""
And lblItemID.Text <> "-1" Then
ItemID = lblItemID.Text
objSQL.RunSQL("Pro_Accounts_Update",
New ObjectPara("@AccountID", ItemID), _
New ObjectPara("@AccountCode", txtAccCode.Text.Trim), _
New ObjectPara("@AccName", txtAccName.Text.Trim), _
New ObjectPara("@AccAddress", txtAccAddress.Text.Trim),
_
New ObjectPara("@AccPhone", txtAccPhone.Text.Trim), _
New ObjectPara("@AccFAX", txtAccFax.Text.Trim), _
New ObjectPara("@AccEmail", txtAccEmail.Text.Trim), _
New ObjectPara("@AccWebsite", txtAccWebsite.Text.Trim),
_
New ObjectPara("@AccDesc", txtDescription.Text.Trim))
Else
'Update Record
ItemID = objSQL.RunSQL("Pro_Accounts_Add",
New ObjectPara("@AccountCode", txtAccCode.Text.Trim), _
New ObjectPara("@AccName", txtAccName.Text.Trim), _
New ObjectPara("@AccAddress", txtAccAddress.Text.Trim),
_
New ObjectPara("@AccPhone", txtAccPhone.Text.Trim), _
New ObjectPara("@AccFAX", txtAccFax.Text.Trim), _
New ObjectPara("@AccEmail", txtAccEmail.Text.Trim), _
New ObjectPara("@AccWebsite", txtAccWebsite.Text.Trim),
_
New ObjectPara("@AccDesc", txtDescription.Text.Trim))
End If
Return ItemID
End Function
Private Sub GetInfo(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
If lblItemID.Text <> ""
And lblItemID.Text <> "-1" Then
Dim objInfo As
DataRow = objSQL.GetRow("Pro_Accounts_Get", New ObjectPara("@AccountID", ItemID))
If Not
objInfo Is Nothing
Then
With objInfo
txtAccCode.Text =
objInfo("AccountCode")
txtAccName.Text =
objInfo("AccName")
txtAccAddress.Text =
objInfo("AccAddress")
txtAccPhone.Text =
objInfo("AccPhone")
txtAccFax.Text =
objInfo("AccFAX")
txtAccEmail.Text =
objInfo("AccEmail")
txtAccWebsite.Text =
objInfo("AccWebsite")
txtDescription.Text =
objInfo("AccDesc")
End With
Else
ResetControls()
End If
Else
ResetControls()
End If
End Sub
#End Region
#Region "Properties"
Public Property
ItemID() As Integer
Get
Return _ItemID
End Get
Set(ByVal Value As Integer)
_ItemID = Value
End Set
End Property
Public Property
ItemName() As String
Get
Return _ItemName
End Get
Set(ByVal Value As String)
_ItemName = Value
End Set
End Property
#End Region
#Region "Event
Handles"
Private Sub
cmdAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdAdd.Click
Dim MyArgs As New MyEventArgs()
ItemID = UpdateRecord()
If ItemID <> -1 Then
ResetControls()
MyArgs.Id = ItemID
MyArgs.SelectedName = ItemName
RaiseEvent OnSelectedRow(Me, MyArgs)
ModalPopupExtender_Popup.Show()
End If
End Sub
Private Sub
cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdUpdate.Click
Dim MyArgs As New MyEventArgs()
ItemID = UpdateRecord()
If ItemID <> -1 Then
ResetControls()
MyArgs.Id = ItemID
MyArgs.SelectedName = ItemName
RaiseEvent OnSelectedRow(Me, MyArgs)
ModalPopupExtender_Popup.Hide()
End If
End Sub
Private Sub
cmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdCancel.Click
ModalPopupExtender_Popup.Hide()
End Sub
Private Sub
cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClose.ServerClick
ModalPopupExtender_Popup.Hide()
End Sub
#End Region
End Class
End Namespace
<%@ Control
Language="vb"
AutoEventWireup="false"
CodeBehind="Popup_ViewRecord.ascx.vb"
Inherits="AddEditRecordsUsingModalPopup.UserControls.Popup_ViewRecord"
%>
<%@ Register
TagPrefix="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:ModalPopupExtender
ID="ModalPopupExtender_Popup"
runat="server"
TargetControlID="cmdShowPopup"
X="620"
Y="150"
PopupControlID="pnlpopup"
CancelControlID="cmdCancel"
BackgroundCssClass="ModalPopupBG"
Drag="True"
/>
<div
class="modal"
style="width:700px;">
<div
class="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="View Record"></asp:label>
</h4>
</div>
<div class="modal-body">
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td colspan="4">
<asp:Label ID="lblItemID"
Visible="false"
runat="server"/>
</td>
</tr>
<tr>
<td>
<asp:label id="plAccountCode"
runat="server"
CssClass="label"
Text="Account
Code"></asp:label>
</td>
<td colspan="3">
<asp:Label ID="lblAccCode"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccName" runat="server" CssClass="label" Text="Account Name"></asp:Label>
</td>
<td colspan="3">
<asp:Label ID="lblAccName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccAddress"
runat="server"
CssClass="label"
Text="Address"></asp:Label>
</td>
<td colspan="3">
<asp:Label ID="lblAccAddress"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td style="width:18%;">
<asp:Label ID="plPhone"
runat="server"
CssClass="label"
Text="Phone"></asp:Label>
</td>
<td style="width:40%;">
<asp:Label ID="lblAccPhone"
runat="server"></asp:Label>
</td>
<td style="width:10%;">
<asp:Label ID="plAccFax"
runat="server"
CssClass="label"
Text="Fax"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccFax"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccEmail"
runat="server"
CssClass="label"
Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccEmail"
runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="plWebsite"
runat="server"
CssClass="label"
Text="Website"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccWebsite"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plDescription"
runat="server"
CssClass="label"
Text="Description"></asp:Label>
</td>
<td colspan="3">
<asp:Label id="lblDescription"
runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdCancel"
runat="server"
CssClass="btn
btn-small" Causesvalidation="false">
<i class="icon-close"></i> <asp:label id="lblClose" runat="server" Text="Close"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel> - B17: Nhập Code phía dưới cho file Popup_ViewRecord.ascx
Namespace AddEditRecordsUsingModalPopup.UserControls
Partial Class Popup_ViewRecord
Inherits System.Web.UI.UserControl
#Region "Private
Members"
Private _ItemID As Integer
#End Region
#Region "Pulbic
Methods"
Public Sub ShowPopup(ByVal ItemID As Integer)
lblItemID.Text = ItemID
GetInfo(ItemID)
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Data
Methods"
Private Sub GetInfo(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
If lblItemID.Text <> ""
And lblItemID.Text <> "-1" Then
Dim objInfo As
DataRow = objSQL.GetRow("Pro_Accounts_Get", New ObjectPara("@AccountID", ItemID))
If Not
objInfo Is Nothing
Then
With objInfo
If Not IsDBNull(objInfo("AccountCode")) Then
lblAccCode.Text =
objInfo("AccountCode")
End If
If Not IsDBNull(objInfo("AccName")) Then
lblAccName.Text =
objInfo("AccName")
End If
If Not IsDBNull(objInfo("AccAddress")) Then
lblAccAddress.Text
= objInfo("AccAddress")
End
If
If Not IsDBNull(objInfo("AccPhone")) Then
lblAccPhone.Text =
objInfo("AccPhone")
End If
If Not IsDBNull(objInfo("AccFAX")) Then
lblAccFax.Text =
objInfo("AccFAX")
End If
If Not IsDBNull(objInfo("AccEmail")) Then
lblAccEmail.Text =
objInfo("AccEmail")
End If
If Not IsDBNull(objInfo("AccWebsite")) Then
lblAccWebsite.Text
= objInfo("AccWebsite")
End If
If Not IsDBNull(objInfo("AccDesc")) Then
lblDescription.Text =
objInfo("AccDesc")
End If
End With
End If
End If
End Sub
#End Region
#Region "Properties"
Public Property
ItemID() As Integer
Get
Return _ItemID
End Get
Set(ByVal Value As Integer)
_ItemID = Value
End Set
End Property
#End Region
#Region "Event
Handles"
Private Sub
cmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdCancel.Click
ModalPopupExtender_Popup.Hide()
End Sub
Private Sub
cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClose.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.
- B18: 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" />- B19: Mở file Default.aspxdưới dạng HTML và bổ xung Control
<%@ Page
Title="Edit
Records with using AJAX Modal Popup Extender in ASP.Net" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb"
Inherits="AddEditRecordsUsingModalPopup._Default"
%>
<%@ Register
TagPrefix="ModalPopup"
TagName="EditRecord"
Src="~/UserControls/Popup_EditRecord.ascx"%>
<%@ Register
TagPrefix="ModalPopup"
TagName="ViewRecord"
Src="~/UserControls/Popup_ViewRecord.ascx"%>
<%@ Register
TagPrefix="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>
Edit
Records with using AJAX Modal Popup Extender in ASP.Net
</h1>
<br />
<ModalPopup:EditRecord ID="ucEditRecord"
runat="server"
/>
<ModalPopup:ViewRecord ID="ucViewRecord"
runat="server"
/>
<ModalPopup:Delete ID="ucDeleteItem"
runat="server"
/>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr>
<td>
<asp:LinkButton id="cmdAdd" runat="server" CssClass="btn btn-small" CausesValidation="false">
<i class="icon-add"></i> <asp:label id="lblAdd" runat="server" Text="Add"></asp:label>
</asp:LinkButton>
</td>
<td
align="right">
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</td>
</tr>
<tr
id="trMessage"
runat="server"
visible="false">
<td
colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td
colspan="2">
<asp:GridView ID="grvObject" runat="server"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="AccountID"
width="100%">
<AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<Columns>
<asp:TemplateField HeaderText="AccountCode">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:LinkButton id="cmdAccountCode"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("AccountID") %>' text='<%# Eval("AccountCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountName">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:LinkButton id="cmdAccountName"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("AccountID") %>' text='<%# Eval("AccName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblAccPhone"
Text='<%# Eval("AccPhone") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FAX">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblAccFAX"
Text='<%# Eval("AccFAX") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblEmail"
Text='<%# Eval("AccEmail") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center"
width="5%"
/>
<ItemTemplate>
<asp:ImageButton ID="cmdEdit"
CommandName="Edit"
CommandArgument='<%# Eval("AccountID")%>' runat="server"
ImageUrl="~/images/edit.gif"
CausesValidation="False"></asp:ImageButton>
<asp:ImageButton ID="cmdDelete"
CommandName="Delete"
CommandArgument='<%# Eval("AccountID")%>' runat="server"
ImageUrl="~/images/delete.gif"
CausesValidation="False"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Imports System.IO
Namespace AddEditRecordsUsingModalPopup
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private Sub
BindAccount()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
updatePanel.Update()
Else
trMessage.Visible = True
grvObject.Visible = False
End If
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@SortField", "CreatedDate"),
_
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "GridView
Methods"
Private Sub
grvObject_RowCommand(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewCommandEventArgs)
Handles grvObject.RowCommand
Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
Select Case
e.CommandName.ToLower
Case "view"
With CType(ucViewRecord,
AddEditRecordsUsingModalPopup.UserControls.Popup_ViewRecord)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Select
End Sub
Private Sub
grvObject_RowEditing(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewEditEventArgs)
Handles grvObject.RowEditing
Dim ItemID As Integer = CType(grvObject.DataKeys(e.NewEditIndex).Value,
Integer)
With CType(ucEditRecord,
AddEditRecordsUsingModalPopup.UserControls.Popup_EditRecord)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Sub
Private Sub
grvObject_RowDeleting(ByVal sender As Object, ByVal e As
System.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,
AddEditRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete)
.ItemID = ItemID
.ShowPopup(ItemID, "")
End With
End If
End Sub
Private Sub grvObject_RowDataBound(ByVal
sender As Object,
ByVal e As GridViewRowEventArgs) Handles
grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
Dim cmdEdit As
ImageButton = DirectCast(e.Row.FindControl("cmdEdit"), ImageButton)
If Not
cmdEdit Is Nothing
Then
cmdEdit.ToolTip = "Edit Account"
End If
'Delete
Dim cmdDelete As
ImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If Not
cmdDelete Is Nothing
Then
cmdDelete.ToolTip = "Delete
Account"
End If
End If
End Sub
#End Region
#Region "Popup"
Private Sub
MySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e As
AddEditRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindAccount()
End If
End With
End Sub
Private Sub
MySelEditRecord_OnSelectedRow(ByVal sender As Object, ByVal e As
AddEditRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindAccount()
End If
End With
End Sub
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
AddHandler CType(ucEditRecord,
AddEditRecordsUsingModalPopup.UserControls.Popup_EditRecord).OnSelectedRow,
AddressOf MySelEditRecord_OnSelectedRow
AddHandler CType(ucDeleteItem,
AddEditRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete).OnSelectedRow,
AddressOf MySelDelete_OnSelectedRow
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindAccount()
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdQuickSearch.Click
BindAccount()
End Sub
Private Sub
cmdAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdAdd.Click
With CType(ucEditRecord,
AddEditRecordsUsingModalPopup.UserControls.Popup_EditRecord)
.ShowPopup(-1)
End With
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.
Chúc các bạn thành công!
Quang Bình
No Comment to " Thêm, sửa, xóa dữ liệu sử dụng AJAX Modal Popup Extender trong ASP.Net "