一个服务器控件能自动保存/加载ASP.NET控件集 原著:Vishal Shukla

本文介绍了一种用于ASP.NET的智能服务器控件,该控件能够保存用户在查询页面上设置的搜索条件,如TEXTBOX、RADIOBUTTON等,并在用户返回页面时恢复这些设置。通过简单地将控件拖放到页面并编辑模板,即可轻松实现搜索条件的记忆功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

俺也不知道怎么翻译好,意思就是说将一些常见的服务器控件如:TEXTBOX,RADIOBUTTON,DROPDOWNLIST,CHECKBOX等控件放入该服务器控件模版内,就能在提交的时候记录这些控件的信息,一般都是用户的搜索条件,如果用户从当前页转到其他页,再转回来时,那些控件上的信息依然保留,用这个控件比较方便,代码改动量非常小,如果想要实现更多的控件信息能保存你需要对该服务器控件做简单的扩展.以下是创建步骤和代码:

一.创建一个ASP .net server control project,重命名默认类比如叫SmartFilter,在SmartFilter中引入System.Design ,该引用使得你可以使用System.Web.UI.Design

二.拷贝以下代码到SmartFilter类,然后编译ASP .net server control project

代码:

  1. 'Imports System
  2. 'Imports System.Collections.Generic
  3. 'Imports System.ComponentModel
  4. 'Imports System.Text
  5. 'Imports System.Web
  6. 'Imports System.Web.UI
  7. 'Imports System.Web.UI.WebControls
  8. '<DefaultProperty("Text"), ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")> _
  9. 'Public Class SmartFilter
  10. '    Inherits WebControl
  11. '    <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property Text() As String
  12. '        Get
  13. '            Dim s As String = CStr(ViewState("Text"))
  14. '            If s Is Nothing Then
  15. '                Return "[" + Me.ID + "]"
  16. '            Else
  17. '                Return s
  18. '            End If
  19. '        End Get
  20. '        Set(ByVal Value As String)
  21. '            ViewState("Text") = Value
  22. '        End Set
  23. '    End Property
  24. '    Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
  25. '        output.Write(Text)
  26. '    End Sub
  27. 'End Class
  28. Option Strict On
  29. Imports System
  30. Imports System.ComponentModel
  31. Imports System.Drawing
  32. Imports System.Security.Permissions
  33. Imports System.Web
  34. Imports System.Web.UI
  35. Imports System.Web.UI.WebControls
  36. Imports System.Web.UI.Design
  37. <AspNetHostingPermission(SecurityAction.Demand, _
  38.         Level:=AspNetHostingPermissionLevel.Minimal), _
  39.     AspNetHostingPermission(SecurityAction.InheritanceDemand, _
  40.         Level:=AspNetHostingPermissionLevel.Minimal), _
  41.     Designer(GetType(SmartFilterDesigner)), _
  42.     DefaultProperty("Title"), _
  43.     ToolboxData( _
  44.         "<{0}:SmartFilter runat=""server""> </{0}:SmartFilter>") _
  45.     > _
  46.     Public Class SmartFilter
  47.     Inherits CompositeControl
  48.     Private _template As ITemplate
  49.     Private _owner As TemplateOwner
  50.     < _
  51.     Bindable(True), _
  52.     Category("Data"), _
  53.     DefaultValue(""), _
  54.     Description("Caption") _
  55.     > _
  56.     Public Overridable Property Caption() As String
  57.         Get
  58.             Dim s As String = CStr(ViewState("Caption"))
  59.             If s Is Nothing Then s = String.Empty
  60.             Return s
  61.         End Get
  62.         Set(ByVal value As String)
  63.             ViewState("Caption") = value
  64.         End Set
  65.     End Property
  66.     < _
  67.     Browsable(False), _
  68.     DesignerSerializationVisibility( _
  69.         DesignerSerializationVisibility.Hidden) _
  70.     > _
  71.     Public ReadOnly Property Owner() As TemplateOwner
  72.         Get
  73.             Return _owner
  74.         End Get
  75.     End Property
  76.     < _
  77.     Browsable(False), _
  78.     PersistenceMode(PersistenceMode.InnerProperty), _
  79.     DefaultValue(GetType(ITemplate), ""), _
  80.     Description("Control template"), _
  81.     TemplateContainer(GetType(SmartFilter)) _
  82.     > _
  83.     Public Overridable Property Template() As ITemplate
  84.         Get
  85.             Return _template
  86.         End Get
  87.         Set(ByVal value As ITemplate)
  88.             _template = value
  89.         End Set
  90.     End Property
  91.     < _
  92.     Bindable(True), _
  93.     Category("Data"), _
  94.     DefaultValue(""), _
  95.     Description("Title"), _
  96.     Localizable(True) _
  97.     > _
  98.     Public Property Title() As String
  99.         Get
  100.             Dim s As String = CStr(ViewState("Title"))
  101.             If s Is Nothing Then s = String.Empty
  102.             Return s
  103.         End Get
  104.         Set(ByVal value As String)
  105.             ViewState("Title") = value
  106.         End Set
  107.     End Property
  108.     Protected Overrides Sub CreateChildControls()
  109.         Controls.Clear()
  110.         _owner = New TemplateOwner()
  111.         Dim temp As ITemplate = _template
  112.         If temp Is Nothing Then
  113.             temp = New DefaultTemplate
  114.         End If
  115.         temp.InstantiateIn(_owner)
  116.         Me.Controls.Add(_owner)
  117.     End Sub
  118.     Public Overrides Sub DataBind()
  119.         If Not ChildControlsCreated Then
  120.             CreateChildControls()
  121.             ChildControlsCreated = True
  122.         End If
  123.         MyBase.DataBind()
  124.     End Sub
  125.     Protected Overrides Sub Finalize()
  126.         MyBase.Finalize()
  127.     End Sub
  128.     Private Sub SmartFilter_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Load
  129.         'This is where all the logic resides
  130.         'If this is NOT a post back we are getting values from session, we will have to change the code to read values from database instead
  131.         'the database will have 5 columns FormId, Control Id, control type, control value and user id
  132.         'For the logged in user (get user id from the context like grid control). Pass the user id and form id to the database which will return 
  133.         ' 3 columns control id, control type and control value for selected combination
  134.         'then loop through the code to read the values from databaset and load them into control. This code is already there.
  135.         'If this is a post back then we need to loop through the controls, read the user selections and send them to database for storing into 
  136.         'profile table so that they can be loaded next time.
  137.         If Not Me.Page.IsPostBack Then
  138.             LoadControlValuesFromProfile()
  139.         Else
  140.             StoreControlValuesToProfile()
  141.         End If
  142.     End Sub
  143.     ' This part of the code can have some more improvements, this can be modified to make sure that the post back done by the page was initiated by search 
  144.     ' button and not some other event. This way we will not store the user's filter criteria on each post back and we can save it only when search is
  145.     ' clicked when there is chance of user changing his search parameters. As soon as this part is done I'll send you guys new code. 
  146.     ' For now the code will work even without this in place just that for each post back we will make a call to database and store the search criterias
  147.     ' for the user
  148.     Private Function GetPostBackControl(ByVal page As Page) As Control
  149.         Dim postbackControlInstance As Control = Nothing
  150.         Dim postbackControlName As String = page.Request.Params.[Get]("__EVENTTARGET")
  151.         If postbackControlName <> Nothing AndAlso postbackControlName <> String.Empty Then
  152.             postbackControlInstance = page.FindControl(postbackControlName)
  153.         Else
  154.             ' handle the Button control postbacks
  155.             Dim i As Integer = 0
  156.             While i < page.Request.Form.Keys.Count
  157.                 postbackControlInstance = page.FindControl(page.Request.Form.Keys(i))
  158.                 If TypeOf postbackControlInstance Is System.Web.UI.WebControls.Button Then
  159.                     Return postbackControlInstance
  160.                 End If
  161.                 System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
  162.             End While
  163.         End If
  164.         ' handle the ImageButton postbacks
  165.         If postbackControlInstance Is Nothing Then
  166.             Dim i As Integer = 0
  167.             While i < page.Request.Form.Count
  168.                 If (page.Request.Form.Keys(i).EndsWith(".x")) OrElse (page.Request.Form.Keys(i).EndsWith(".y")) Then
  169.                     postbackControlInstance = page.FindControl(page.Request.Form.Keys(i).Substring(0, page.Request.Form.Keys(i).Length - 2))
  170.                     Return postbackControlInstance
  171.                 End If
  172.                 System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
  173.             End While
  174.         End If
  175.         Return postbackControlInstance
  176.     End Function
  177.     Private Sub LoadControlValuesFromProfile()
  178.         If Not IsNothing(HttpContext.Current.Session(Me.Page.Form.ID)) Then
  179.             ' If child controls are not created yet then create.
  180.             If Not ChildControlsCreated Then
  181.                 CreateChildControls()
  182.                 ChildControlsCreated = True
  183.             End If
  184.             ' Get value from datasource for filter control.
  185.             Dim objArray As ArrayList
  186.             objArray = CType(HttpContext.Current.Session(Me.Page.Form.ID), ArrayList)
  187.             For Each objControl In objArray
  188.                 Dim objControlInfo As ArrayList = CType(objControl, ArrayList)
  189.                 ' populate filter control with history data.
  190.                 Select Case objControlInfo(0).ToString
  191.                     Case "textbox"
  192.                         CType(_owner.FindControl(objControlInfo(1).ToString), TextBox).Text = objControlInfo(2).ToString
  193.                     Case "dropdownlist"
  194.                         CType(_owner.FindControl(objControlInfo(1).ToString), DropDownList).SelectedValue = objControlInfo(2).ToString
  195.                     Case "checkbox"
  196.                         CType(_owner.FindControl(objControlInfo(1).ToString), CheckBox).Checked = CType(objControlInfo(2).ToString, Boolean)
  197.                     Case "radiobutton"
  198.                         CType(_owner.FindControl(objControlInfo(1).ToString), RadioButton).Checked = CType(objControlInfo(2).ToString, Boolean)
  199.                     Case Else
  200.                         ' Do nothing.
  201.                 End Select
  202.             Next
  203.         End If
  204.     End Sub
  205.     Private Sub StoreControlValuesToProfile()
  206.         ' Insert data into datasource from filter control.
  207.         Dim objArray As New ArrayList
  208.         For Each objControl In _owner.Controls
  209.             Dim objControlInfo As New ArrayList
  210.             Select Case objControl.GetType.Name.ToLower()
  211.                 Case "textbox"
  212.                     objControlInfo.Add("textbox")
  213.                     objControlInfo.Add(CType(objControl, WebControl).ID)
  214.                     objControlInfo.Add(CType(objControl, TextBox).Text)
  215.                 Case "dropdownlist"
  216.                     objControlInfo.Add("dropdownlist")
  217.                     objControlInfo.Add(CType(objControl, WebControl).ID)
  218.                     objControlInfo.Add(CType(objControl, DropDownList).SelectedValue)
  219.                 Case "checkbox"
  220.                     objControlInfo.Add("checkbox")
  221.                     objControlInfo.Add(CType(objControl, WebControl).ID)
  222.                     objControlInfo.Add(CType(objControl, CheckBox).Checked.ToString)
  223.                 Case "radiobutton"
  224.                     objControlInfo.Add("radiobutton")
  225.                     objControlInfo.Add(CType(objControl, WebControl).ID)
  226.                     objControlInfo.Add(CType(objControl, RadioButton).Checked.ToString)
  227.                 Case Else
  228.                     ' Do nothing
  229.             End Select
  230.             If objControlInfo.Count <> 0 Then
  231.                 objArray.Add(objControlInfo)
  232.             End If
  233.         Next
  234.         HttpContext.Current.Session(Me.Page.Form.ID) = objArray
  235.     End Sub
  236. End Class
  237. <ToolboxItem(False)> _
  238. Public Class TemplateOwner
  239.     Inherits WebControl
  240. End Class
  241. #Region "DefaultTemplate"
  242. NotInheritable Class DefaultTemplate
  243.     Implements ITemplate
  244.     Sub InstantiateIn(ByVal owner As Control) _
  245.         Implements ITemplate.InstantiateIn
  246.         Dim title As New Label
  247.         AddHandler title.DataBinding, AddressOf title_DataBinding
  248.         Dim linebreak As New LiteralControl("<br/>")
  249.         Dim caption As New Label
  250.         AddHandler caption.DataBinding, _
  251.             AddressOf caption_DataBinding
  252.         owner.Controls.Add(title)
  253.         owner.Controls.Add(linebreak)
  254.         owner.Controls.Add(caption)
  255.         For Each objControl In owner.Controls
  256.             ' = objControl.ToString
  257.         Next
  258.     End Sub
  259.     Sub caption_DataBinding(ByVal sender As Object, _
  260.         ByVal e As EventArgs)
  261.         Dim source As Label = CType(sender, Label)
  262.         Dim container As SmartFilter = _
  263.             CType(source.NamingContainer, SmartFilter)
  264.         source.Text = container.Caption
  265.     End Sub
  266.     Sub title_DataBinding(ByVal sender As Object, _
  267.         ByVal e As EventArgs)
  268.         Dim source As Label = CType(sender, Label)
  269.         Dim container As SmartFilter = _
  270.             CType(source.NamingContainer, SmartFilter)
  271.         source.Text = container.Caption
  272.     End Sub
  273. End Class
  274. #End Region
  275. Public Class SmartFilterDesigner
  276.     Inherits ControlDesigner
  277.     Public Overrides Sub Initialize(ByVal Component As IComponent)
  278.         MyBase.Initialize(Component)
  279.         SetViewFlags(ViewFlags.TemplateEditing, True)
  280.     End Sub
  281.     Public Overloads Overrides Function GetDesignTimeHtml() As String
  282.         Return "<span>This is design-time HTML</span>"
  283.     End Function
  284.     Public Overrides ReadOnly Property TemplateGroups() As TemplateGroupCollection
  285.         Get
  286.             Dim collection As New TemplateGroupCollection
  287.             Dim group As TemplateGroup
  288.             Dim template As TemplateDefinition
  289.             Dim control As SmartFilter
  290.             control = CType(Component, SmartFilter)
  291.             group = New TemplateGroup("Item")
  292.             template = New TemplateDefinition(Me"Template", control, "Template"True)
  293.             group.AddTemplateDefinition(template)
  294.             collection.Add(group)
  295.             Return collection
  296.         End Get
  297.     End Property
  298. End Class

现在该服务器控件就创建完成了,接下来就是怎么使用他了.

三.使用该控件.

比如有个查询页面叫search.aspx,该页面是提供给客户查询信息的,里面假如有一些提供查询条件的服务器控件,比如TEXTBOX,RADIOBUTTON,DROPDOWNLIST,CHECKBOX.将该控件拖到search.aspx活动页面文件,点击该控件的"Edit Templates"属性,将TEXTBOX,RADIOBUTTON,DROPDOWNLIST,CHECKBOX控件放入Templates中,也可以通过页面前端代码加入:比如

 <cc1:SmartFilter ID="SmartFilter1" runat="server">
        <Template>
            <asp:Label ID="Label3" runat="server" Text="Textbox"></asp:Label>
            <asp:TextBox ID="Txt1" runat="server"></asp:TextBox>
      <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem Text="East" Value="east" Selected="True"></asp:ListItem>
                <asp:ListItem Text="West" Value="west"></asp:ListItem>
                <asp:ListItem Text="South" Value="south"></asp:ListItem>
                <asp:ListItem Text="North" Value="north"></asp:ListItem>
            </asp:DropDownList>
            <asp:CheckBox ID="CheckBox1" runat="server"  Text="Is this a cool code" Checked="true"/>
            <asp:RadioButton ID="RadioButton1" runat="server"  Text="Radio Button"/>
            <asp:Button ID="Button3" runat="server" Text="Button" onclick="Button3_Click" />
        </Template>
        </cc1:SmartFilter>

好了,就是这样了,懒地写了,还没吃早饭,有问题的可以直接问我,联系方式BLOG上有

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值