(Create Dynamic jquery Accordion in Asp.net) – Có nhiều cách để tạo Accordion động mà thủ thuật lập trình đã giới thiệu với các bạn như: sử dụng Bootstrap, sử dụng AjaxControlToolkit. Ngoài 2 cách trên, hôm nay thủ thuật lập trình sẽ giới thiệu với các bạn thêm 1 cách nữa để có thể tạo Accordion động, đó là sử dụng thư viện jQuery. Với ví dụ dưới đây, tên các khách hàng sẽ được hiển thị và khi kích vào tên thông tin chi tiết sẽ được hiển thị.
- B1: Tạo CSDL SQL Customers
- B2: Tạo Bảng Accounts có cấu trúc phía dưới trong CSDL 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
USE [Customers]
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
- 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.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace DynamicAccordionUsingjQuery
{
public class SqlDataProvider
{
#region"Membres Prives"
private string_connectionString;
#endregion
#region"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region"Proprietes"
public stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
if (Para != null)
{
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
}
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(stringPname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace DynamicAccordionUsingjQuery
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
If NotPara Is NothingThen
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
#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
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B5: Mở file Default.aspxdưới dạng HTML và nhập mã HTML
<%@ PageTitle="Dynamic Accordion Using jQuery in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="DynamicAccordionUsingjQuery._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h1>
Dynamic Accordion Using jQuery in ASP.Net
</h1>
<br />
<link type="text/css"href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/blitzer/jquery-ui.css"rel="Stylesheet"/>
<script type="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js"></script>
<script type="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.6/jquery-ui.js"></script>
<script language="javascript"type="text/javascript">
$(function () {
$("#accordion").accordion();
});
</script>
<div id="accordion"style="width:500px;">
<asp:Repeater ID="repAccordion"runat="server">
<ItemTemplate>
<h3><a href="#"><%# Eval("AccName")%></a></h3>
<div>
<tablecellpadding="1"cellspacing="2"width="100%">
<tr>
<td style="width:20%;">
<b>Email</b>
</td>
<td>
<%# Eval("AccEmail")%>
</td>
</tr>
<tr>
<td>
<b>Phone</b>
</td>
<td>
<%# Eval("AccPhone")%>
</td>
</tr>
<tr>
<td>
<b>Fax</b>
</td>
<td>
<%# Eval("AccFAX")%>
</td>
</tr>
<tr>
<td>
<b>Address</b>
</td>
<td>
<%# Eval("AccAddress")%>
</td>
</tr>
<tr>
<td>
<b>Website</b>
</td>
<td>
<%# Eval("AccWebsite")%>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</asp:Content>
- B6: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DynamicAccordionUsingjQuery
{
public partial class _Default : System.Web.UI.Page
{
#region"Create Accordion"
private voidCreateAccordion()
{
DataTable objBind = newDataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
repAccordion.DataSource = objBind;
repAccordion.DataBind();
}
}
}
private DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Accounts_List", new ObjectPara("@Keyword", ""), new ObjectPara("@SortField", "CreatedDate"), new ObjectPara("@SortType", "DESC"));
return objBind;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
CreateAccordion();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
Imports System.IO
Namespace DynamicAccordionUsingjQuery
Public Class _Default
Inherits System.Web.UI.Page
#Region "Create Accordion"
Private SubCreateAccordion()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
repAccordion.DataSource = objBind
repAccordion.DataBind()
End If
End If
End Sub
#End Region
#Region "Bind Data"
Private FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", ""), _
New ObjectPara("@SortField", "CreatedDate"), _
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
CreateAccordion()
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. Mỗi khi click vào tên khách hàng các thông tin chi tiết về khách hàng này sẽ được hiển thị.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment