Tìm kiếm dữ liệu sử dụng AJAX Modal Popup Extender trong ASP.Net
(Tìm kiếm với Modal Popup trong Asp.net) – Trong các Form nhập dữ liệu, để tìm kiếm và chọn nhanh thông tin từ bảng dữ liệu khác, các lập trình viên thường sử dụng 1 trong 2 cách đó là: Autocomplete hoặc Popup. Mỗi cách sử dụng có những ưu nhược điểm khác nhau, với Autocomplete người sử dụng không phải mất thêm nhiều thao tác kích để chọn dữ liệu, nhưng với dữ liệu có nhiều tiêu chí để tìm thì phải sử dụng Popup. Với Popup người sử dụng sẽ mất thêm thao tác nhưng khi cần nhiều tiêu chí để tìm kiếm chính xác dữ liệu thì Popup sẽ giúp người lập trình giải quyết được vấn đề này. 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 tìm kiếm dữ liệu một cách nhanh chóng, thuận tiện và dễ dàng.
- 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: Tạo Bảng Contacts có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | ContactID | Int | Trường tự tăng |
2 | AccountID | Int | |
3 | ContactCode | nvarchar(25) | |
4 | ContactName | nvarchar(250) | |
5 | Sex | bit | |
6 | Birthdate | datetime | |
7 | ContactAddress | nvarchar(250) | |
8 | Mobille | nvarchar(50) | |
9 | nvarchar(150) | ||
10 | CreatedDate | datetime | |
11 | ModifiedDate | datetime |
- B4: Tạo các stored procedure trong SQL Server
- 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 SearchRecordsUsingModalPopup
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-delete {
background-image: url(Images/delete.gif);
background-position: center
center;
height: 16px;
width: 16px;
}
.icon-search {
background-image: url(Images/search.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;}
+ edit.gif, delete.gif, icon_search.gif, clear.gif vào thư mục Images
+ no.png, yes.png, sprite.png, add.gif, delete.gif, edit.gif, lt.gif, save.gif, search.gif vào thư mục Styles\Images
- B12: Tạo thư mục UserControls và thêm file Popup_SearchRecord.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_SearchRecord.ascx.vb"
Inherits="SearchRecordsUsingModalPopup.UserControls.Popup_SearchRecord"
%>
<%@ 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="700"
Y="150"
PopupControlID="pnlpopup"
CancelControlID="cmdCancel"
BackgroundCssClass="ModalPopupBG"
Drag="True"
/>
<div
class="modal"
style="width:520px;">
<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="Search
Account"></asp:label>
</h4>
</div>
<div class="modal-body">
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td>
<asp:label id="plKeyword"
runat="server"
CssClass="CRM_Label"
Text="Keyword"></asp:label>
</td>
<td>
<asp:TextBox ID="txtKeyword"
CssClass="form-control"
runat="server"
Width="400px"></asp:TextBox>
</td>
</tr>
<tr id="trMessage"
runat="server">
<td colspan="2" align="left"
style="padding:2px;">
<asp:Label ID="lblMessage"
CssClass="label"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" style="padding-top:8px;padding-bottom:5px;">
<div
class="btn-group">
<asp:LinkButton id="cmdSearch"
runat="server"
CssClass="btn
btn-small" CausesValidation="false">
<i class="icon-search"></i> <asp:label id="lblSearch" runat="server" Text="Search"></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>
</td>
</tr>
</table>
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td>
<asp:GridView ID="grvObject"
runat="server"
AllowPaging="true"
PageSize="8"
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="AccountID"
Visible="false">
<ItemStyle
width="1%"
/>
<ItemTemplate>
<asp:Label id="lblAccountID"
runat="server"
text='<%# Eval("AccountID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountCode">
<ItemStyle
width="30%"
/>
<ItemTemplate>
<asp:LinkButton id="cmdAccountCode"
runat="server"
CausesValidation="False"
CommandName="Select"
CommandArgument='<%# Eval("AccountID") %>' text='<%# Eval("AccountCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountName">
<ItemStyle width="70%" />
<ItemTemplate>
<asp:LinkButton CausesValidation="false"
ID="cmdAccountName"
Text='<%#Eval("AccName")%>' CommandName="Select"
runat="server"
CommandArgument='<%# Eval("AccountID")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel> - B13: Nhập Code phía dưới cho file Popup_SearchRecord.ascx
Namespace SearchRecordsUsingModalPopup.UserControls
Partial Class Popup_SearchRecord
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 "Pulbic
Methods"
Public Sub
ShowPopup()
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "GetData"
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
lblMessage.Text = "Total "
& objBind.Rows.Count & " record"
Else
grvObject.Visible = False
lblMessage.Text = "No matching record(s) found"
End If
Else
lblMessage.Text = "No matching
record(s) found"
End If
trMessage.Visible = True
updatePanelPopup.Update()
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", txtKeyword.Text.Trim), _
New ObjectPara("@SortField", "CreatedDate"),
_
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "DataGrid
Methods"
Private Function
GetGridViewRowItemID(ByVal row As GridViewRow) As Integer
Dim lblAccountID As Label = DirectCast(row.FindControl("lblAccountID"), Label)
If lblAccountID Is Nothing Then
Throw New
Exception("AccountID:
could not find AccountID control!")
End If
Return Convert.ToInt32(lblAccountID.Text)
End Function
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindAccount()
ModalPopupExtender_Popup.Show()
End Sub
Public Sub
grvObject_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles
grvObject.SelectedIndexChanged
Dim AccountID As Integer = GetGridViewRowItemID(grvObject.SelectedRow)
Dim objSQL As New SqlDataProvider
Dim MyArgs As New MyEventArgs()
ModalPopupExtender_Popup.Hide()
ScriptManager.GetCurrent(Page).RegisterDataItem(grvObject,
grvObject.SelectedIndex.ToString)
If AccountID <> -1 Then
Dim
objInfo As DataRow
= objSQL.GetRow("Pro_Accounts_Get",
New ObjectPara("@AccountID", AccountID))
If Not
objInfo Is Nothing
Then
With objInfo
MyArgs.Id = objInfo("AccountID")
MyArgs.SelectedName = objInfo("AccName")
RaiseEvent OnSelectedRow(Me,
MyArgs)
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
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"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
End If
Catch ex As Exception
End Try
End Sub
Private Sub cmdSearch_Click(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles
cmdSearch.Click
BindAccount()
ModalPopupExtender_Popup.Show()
End Sub
Private Sub
cmdCancel_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.
- B14: 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" />- B15: Tạo file EditContact.aspx và mở file dưới dạng HTML, nhập mã HTML
<%@ Page
Title="Search
Records with using AJAX Modal Popup Extender in ASP.Net" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="EditContact.aspx.vb"
Inherits="SearchRecordsUsingModalPopup.EditContact"
%>
<%@ Register
TagPrefix="ModalPopup"
TagName="Search"
Src="~/UserControls/Popup_SearchRecord.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>
<ModalPopup:Search ID="ucSearchRecord"
runat="server"
/>
<ModalPopup:Delete ID="ucDeleteItem"
runat="server"
/>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellspacing="0"
cellpadding="0"
border="0"
width="75%">
<tr>
<td>
<div class="panel panel-default">
<div class="panel-heading">
<asp:label id="lblHeader"
runat="server"></asp:label>
</div>
<div class="panel-body">
<table cellspacing="2"
cellpadding="3"
border="0"
width="100%">
<tr>
<td>
<asp:label id="plContactCode"
runat="server"
CssClass="label"
Text="ContactCode
(*)"></asp:label>
</td>
<td>
<asp:TextBox ID="txtContactCode"
CssClass="form-control"
runat="server"
Width="150px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valContactCode"
CssClass="alert-error"
runat="server"
ControlToValidate="txtContactCode"
Display="dynamic"
ErrorMessage="Enter
Contact Code"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="plContactName"
runat="server"
CssClass="label"
Text="Contact Name
(*)"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtContactName" CssClass="form-control" runat="server" width="220px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valContactName"
CssClass="alert-error"
runat="server"
ControlToValidate="txtContactName"
Display="dynamic"
ErrorMessage="Enter
Contact Name"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccountName"
runat="server"
CssClass="label"
Text="AccountName
(*)"></asp:Label>
</td>
<td colspan="3">
<asp:TextBox ID="txtAccountName"
CssClass="form-control"
runat="server"
width="510px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="valAccountName"
CssClass="alert-error"
runat="server"
ControlToValidate="txtAccountName"
Display="dynamic"
ErrorMessage="Enter
Account Name"></asp:RequiredFieldValidator>
<asp:Label ID="lblAccountID"
runat="server"
Visible="false"></asp:Label>
<asp:ImageButton ID="cmdSearchAccount"
runat="server"
causesvalidation="false"
ToolTip="Search
Account" imageurl="~/images/icon_search.gif"></asp:ImageButton>
<asp:ImageButton ID="cmdClear"
runat="server"
causesvalidation="false"
ToolTip="Clear"
imageurl="~/images/clear.gif"></asp:ImageButton>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAddress"
runat="server"
CssClass="label"
Text="Address"></asp:Label>
</td>
<td colspan="3">
<asp:TextBox ID="txtAddress"
CssClass="form-control"
TextMode="multiLine"
runat="server"
Height="45px"
width="560px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width:48%;">
<asp:Label ID="plSex" runat="server"
CssClass="label"
Text="Sex"></asp:Label>
</td>
<td style="width:40%;">
<asp:RadioButtonList ID="rdoSex" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Value="1" Text="Male" Selected="True"></asp:ListItem>
<asp:ListItem Value="0" Text="Female"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td style="width:10%;">
<asp:Label ID="plBirthdate"
runat="server"
CssClass="label"
Text="Birthdate"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtBirthdate"
CssClass="form-control"
runat="server"
width="220px"></asp:TextBox>
<asp:CompareValidator ID="cvBirthDate"
CssClass="alert-error"
ControlToValidate="txtBirthdate"
Display="dynamic"
Operator="DataTypeCheck"
ErrorMessage="Error
Birthdate" Type="date" runat="server"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plEmail"
runat="server"
CssClass="label"
Text="Email"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" CssClass="form-control" runat="server" width="220px"></asp:TextBox>
<asp:regularexpressionvalidator
id="cvEmail"
CssClass="alert-error"
runat="server"
ErrorMessage="Error
Email" ControlToValidate="txtEmail" Display="Dynamic" ValidationExpression="[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+"></asp:regularexpressionvalidator>
</td>
<td>
<asp:Label ID="plMobille" runat="server" CssClass="label" Text="Mobille"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtMobille"
CssClass="form-control"
runat="server"
width="220px"></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="cmdDelete"
runat="server"
CssClass="btn
btn-small" Causesvalidation="false">
<i class="icon-delete"></i> <asp:label id="lblDelete" runat="server" Text="Delete"></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="Back"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B16: Nhập Code cho file EditContact.aspx
Imports System.IO
Namespace SearchRecordsUsingModalPopup
Public Class EditContact
Inherits System.Web.UI.Page
#Region "Private
Member"
Private ContactID As Integer = -1
#End Region
#Region "Private
Methods"
Private Sub
SetTitle()
If ContactID <> -1 And
ContactID <> 1 Then
lblHeader.Text = "Edit Contact"
Else
lblHeader.Text = "Add Contact"
End If
End Sub
Private Sub
ResetControls()
txtContactCode.Text = ""
txtContactName.Text = ""
txtAccountName.Text = ""
lblAccountID.Text = ""
txtAddress.Text = ""
txtBirthdate.Text = ""
txtEmail.Text = ""
txtMobille.Text = ""
End Sub
#End Region
#Region "Save Data"
Private Sub SaveData(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
Dim AccountID As Integer = -1
If lblAccountID.Text <> "" Then
AccountID = lblAccountID.Text
End If
'Update Record
If ItemID <> -1 And
ItemID <> 0 Then
objSQL.RunSQL("Pro_Contacts_Update",
New ObjectPara("@ContactID", ItemID), _
New ObjectPara("@AccountID", AccountID), _
New ObjectPara("@ContactCode",
txtContactCode.Text.Trim), _
New ObjectPara("@ContactName",
txtContactName.Text.Trim), _
New ObjectPara("@Sex", rdoSex.SelectedValue), _
New ObjectPara("@Birthdate", txtBirthdate.Text.Trim), _
New ObjectPara("@ContactAddress",
txtAddress.Text.Trim), _
New ObjectPara("@Mobille", txtMobille.Text.Trim), _
New
ObjectPara("@Email",
txtEmail.Text.Trim))
Else
'Add Record
ItemID = objSQL.RunSQL("Pro_Contacts_Add",
New ObjectPara("@AccountID", AccountID), _
New ObjectPara("@ContactCode",
txtContactCode.Text.Trim), _
New ObjectPara("@ContactName",
txtContactName.Text.Trim), _
New
ObjectPara("@Sex",
rdoSex.SelectedValue), _
New ObjectPara("@Birthdate", txtBirthdate.Text.Trim), _
New ObjectPara("@ContactAddress",
txtAddress.Text.Trim), _
New ObjectPara("@Mobille", txtMobille.Text.Trim), _
New ObjectPara("@Email", txtEmail.Text.Trim))
End If
End Sub
#End Region
#Region "GetInfo"
Private Sub GetInfo(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
If ItemID <> -1 Then
Dim objInfo As
DataRow = objSQL.GetRow("Pro_Contacts_Get", New ObjectPara("@ContactID", ItemID))
If Not
objInfo Is Nothing
Then
With objInfo
txtContactCode.Text =
objInfo("ContactCode")
txtContactName.Text =
objInfo("ContactName")
If Not IsDBNull(objInfo("AccountID")) Then
lblAccountID.Text =
objInfo("AccountID")
End If
If Not IsDBNull(objInfo("AccName")) Then
txtAccountName.Text
= objInfo("AccName")
End If
If Not IsDBNull(objInfo("ContactAddress")) Then
txtAddress.Text =
objInfo("ContactAddress")
End
If
If Not IsDBNull(objInfo("Sex")) Then
If objInfo("Sex")
Then
rdoSex.SelectedValue = "1"
Else
rdoSex.SelectedValue = "0"
End If
Else
rdoSex.SelectedValue = "0"
End If
If Not IsDBNull(objInfo("Birthdate")) Then
txtBirthdate.Text =
CType(objInfo("Birthdate"),
Date).ToShortDateString
End If
If Not IsDBNull(objInfo("Email")) Then
txtEmail.Text =
objInfo("Email")
End If
If Not IsDBNull(objInfo("Mobille")) Then
txtMobille.Text =
objInfo("Mobille")
End If
End With
End If
End If
End Sub
#End Region
#Region "Popup"
Private Sub
MySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e As
SearchRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
Response.Redirect("Default.aspx")
End If
End With
End Sub
Private Sub
MySelSearchRecord_OnSelectedRow(ByVal sender As Object, ByVal e As SearchRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If .Id <> ""
Then
txtAccountName.Text = .SelectedName
lblAccountID.Text = .Id
End If
updatePanel.Update()
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
If Not
Request.QueryString("ContactID") Is Nothing Then
ContactID = Request.QueryString("ContactID")
End If
AddHandler CType(ucSearchRecord,
SearchRecordsUsingModalPopup.UserControls.Popup_SearchRecord).OnSelectedRow,
AddressOf MySelSearchRecord_OnSelectedRow
AddHandler CType(ucDeleteItem,
SearchRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete).OnSelectedRow,
AddressOf MySelDelete_OnSelectedRow
If Page.IsPostBack = False Then
lblAccountID.Text = ""
SetTitle()
If ContactID <> -1 Then
GetInfo(ContactID)
cmdDelete.Visible = True
Else
cmdDelete.Visible = False
End If
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdAdd.Click
SaveData(ContactID)
ResetControls()
Response.Redirect("EditContact.aspx")
End Sub
Private Sub
cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdUpdate.Click
SaveData(ContactID)
Response.Redirect("Default.aspx")
End Sub
Private Sub
cmdDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdDelete.Click
With CType(ucDeleteItem,
SearchRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete)
.ItemID = ContactID
.ShowPopup(ContactID, "")
End With
End Sub
Private Sub
cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdCancel.Click
Response.Redirect("Default.aspx")
End Sub
Private Sub
cmdSearchAccount_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdSearchAccount.Click
With CType(ucSearchRecord,
SearchRecordsUsingModalPopup.UserControls.Popup_SearchRecord)
.ShowPopup()
End With
End Sub
Private Sub
cmdClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClear.Click
txtAccountName.Text = ""
lblAccountID.Text = ""
updatePanel.Update()
End Sub
#End Region
End Class
End Namespace
<%@ Page
Title="Search
Records with using AJAX Modal Popup Extender in ASP.Net" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb"
Inherits="SearchRecordsUsingModalPopup._Default"
%>
<%@ Register
TagPrefix="ModalPopup"
TagName="ViewRecord"
Src="~/UserControls/Popup_ViewRecord.ascx"%>
<%@ Register
TagPrefix="ModalPopup"
TagName="Delete"
Src="~/UserControls/Popup_ConfirmDelete.ascx"%>
<%@ Register
TagPrefix="ModalPopup"
TagName="Search"
Src="~/UserControls/Popup_SearchRecord.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h1>
Search Records with using AJAX Modal Popup Extender in ASP.Net
</h1>
<br />
<ModalPopup:ViewRecord ID="ucViewRecord"
runat="server"
/>
<ModalPopup:Delete ID="ucDeleteItem"
runat="server"
/>
<ModalPopup:Search ID="ucSearchRecord"
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:Label ID="plFilter" runat="server" Text="Filter By Account"></asp:Label>
<asp:TextBox ID="txtAccountName" CssClass="form-control" ToolTip="Enter Account" runat="server" width="200px"></asp:TextBox>
<asp:Label ID="lblAccountID" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="cmdSearchAccount" runat="server" causesvalidation="false"
ToolTip="Search
Account" imageurl="~/images/icon_search.gif"></asp:ImageButton>
<asp:ImageButton ID="cmdClear" runat="server" causesvalidation="false" ToolTip="Clear" imageurl="~/images/clear.gif"></asp:ImageButton>
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<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="ContactID"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<Columns>
<asp:TemplateField HeaderText="ContactCode">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:LinkButton id="cmdContactCode"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("ContactID") %>' text='<%# Eval("ContactCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContactName">
<ItemStyle width="12%" />
<ItemTemplate>
<asp:LinkButton id="cmdContactName"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("ContactID") %>' text='<%# Eval("ContactName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Birthdate">
<ItemStyle HorizontalAlign="Center"
width="8%"
/>
<ItemTemplate>
<asp:Label ID="lblBirthdate"
Text='<%# Eval("Birthdate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobille">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblMobille"
Text='<%# Eval("Mobille") %>' 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:HyperLink ID="cmdEdit"
CommandArgument='<%# Eval("ContactID")%>' runat="server"
ImageUrl="~/images/edit.gif"></asp:HyperLink>
<asp:ImageButton ID="cmdDelete"
CommandName="Delete"
CommandArgument='<%# Eval("ContactID")%>' 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 SearchRecordsUsingModalPopup
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private Sub
BindContact()
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
Else
trMessage.Visible = True
grvObject.Visible = False
End If
updatePanel.Update()
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim AccountID As Integer = -1
If lblAccountID.Text <> "" Then
AccountID = lblAccountID.Text.Trim
End If
Dim objBind As DataTable = objSQL.FillTable("Pro_Contacts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@AccountID", AccountID), _
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,
SearchRecordsUsingModalPopup.UserControls.Popup_ViewRecord)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Select
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,
SearchRecordsUsingModalPopup.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 ContactID As
Integer = DataBinder.Eval(e.Row.DataItem,
"ContactID")
Dim cmdEdit As
HyperLink = DirectCast(e.Row.FindControl("cmdEdit"), HyperLink)
If Not
cmdEdit Is Nothing
Then
cmdEdit.ToolTip = "Edit Contact"
cmdEdit.NavigateUrl = "EditContact.aspx?ContactID="
& ContactID
End If
'Delete
Dim
cmdDelete As ImageButton
= DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If Not
cmdDelete Is Nothing
Then
cmdDelete.ToolTip = "Delete
Contact"
End If
End If
End Sub
#End Region
#Region "Popup"
Private Sub
MySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e As
SearchRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindContact()
End If
End With
End Sub
Private Sub
MySelSearchRecord_OnSelectedRow(ByVal sender As Object, ByVal e As
SearchRecordsUsingModalPopup.MyEventArgs)
Dim ItemName As String = ""
With e
If .Id <> ""
Then
txtAccountName.Text = .SelectedName
lblAccountID.Text = .Id
BindContact()
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(ucSearchRecord,
SearchRecordsUsingModalPopup.UserControls.Popup_SearchRecord).OnSelectedRow,
AddressOf MySelSearchRecord_OnSelectedRow
AddHandler CType(ucDeleteItem,
SearchRecordsUsingModalPopup.UserControls.Popup_ConfirmDelete).OnSelectedRow,
AddressOf MySelDelete_OnSelectedRow
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindContact()
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdAdd.Click
Response.Redirect("EditContact.aspx")
End Sub
Private Sub
cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdQuickSearch.Click
BindContact()
End Sub
Private Sub
cmdSearchAccount_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdSearchAccount.Click
With CType(ucSearchRecord,
SearchRecordsUsingModalPopup.UserControls.Popup_SearchRecord)
.ShowPopup()
End With
End Sub
Private Sub
cmdClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClear.Click
txtAccountName.Text = ""
lblAccountID.Text = ""
BindContact()
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 " Tìm kiếm dữ liệu sử dụng AJAX Modal Popup Extender trong ASP.Net "