visualstudio2008-如果需要,让asp.net用户控件只发出一次SCRIPT块



我正在寻求如何最好地封装这种HTML标记和行为以进行广泛重用的建议。

我已经在给定的.aspx页面上开发了一些"上下文相关"帮助的工作版本,该页面使用了jQuery的qTip2插件(为了完整起见,此处为"压缩"):

$('a.myMore[title]').qtip({
    content: {  title: { button: true } }
    , style: { classes: 'qtip-youtube myCustomClass' }
    , position: { target: 'mouse',  adjust: { x: 5, y: 5} }
    , show: { effect: function() {  $(this).fadeTo(500, 1); } }
    , events:{hide:function(event, api) {if (event.originalEvent.type !== 'click') return false;}}
});

下面是上面插件操作的标记示例,我想封装它:

<a class="myMore" href="#" title='Text here will be displayed by a jQuery plugin called qTip2'>
   <img src='../images/icon/info1.png' alt='?' />
</a>

这是在使用VB.Net的Visual Studio 2008 web窗体的旧环境中。SO上的一个线程很好地表达了我的需求-请参阅MVC3 Razor视图-但我能想到的唯一封装方法是编写一个ASP.Net web用户控件(.ascx)来转储我所需的HTML。我设想能够在我的.aspx页面上撒上这样的东西:

<qTipH:qTipHelper Title="Here is some content for the qTip." runat="server" />

考虑到我必须工作的"旧"环境,我是否走上了正轨

我开始编写这个控件,并立即注意到这些服务器控件中的任何一个都没有title属性-<asp:HyperLink nor <asp:ImageButton nor <asp:LinkButton。我不认为用户控件后面的代码可以将title属性文本注入到标准的HTML<a>标记中。

我想我知道我需要渲染什么,但我正在寻找最佳方法的建议。谢谢

编辑-更新:

这是我的.ascx文件:

<%@ Control Language="vb" AutoEventWireup="false" 
  CodeBehind="qTipHelper.ascx.vb"
  Inherits="myProjectName.qTipHelper" %>
<asp:HyperLink ID="HyperLink1" runat="server" CssClass="myMore"></asp:HyperLink>

我发现,任何"丢失"的属性(如"title")都可以通过以下代码来处理,这些代码添加到控件的attributes集合中:

Public Partial Class qTipHelper
Inherits System.Web.UI.UserControl
Public Title As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Title Is Nothing OrElse Title = "" Then
        Visible = False
Else
    Dim encodedTitle As String = Server.HtmlEncode(Title)
    HyperLink1.Attributes.Add("title", encodedTitle)
    HyperLink1.Attributes.Add("href", "#")
    HyperLink1.ImageUrl = "../images/icon/info1.png"
End If
End Sub
End Class

在我的调用页面上,我添加了以下内容:

<%@ Register  TagPrefix="qTip" TagName="qTipHelper" Src="~/UserControls/qTipHelper.ascx" %> 

然后为了吐出HTML,我添加了以下内容:

<qTip:qTipHelper runat="server" title="grist for the mill courtesy of qTip" >
        </qTip:qTipHelper>

是否有一种编码技术可以添加到用户控件中,在页面底部发出一个Javascript脚本块(假设上面的HTML中存在一个或多个qTipHelper标签)?

回想起来,这是一个奇怪的问题(我想是因为我以前从未做过这样的事情)。。。

无论如何,我只是将qtip的所有当前使用收集在一个Javascript文件中,我在每个使用它的.aspx页面的底部引用该文件:

<script type="text/javascript" src="<%= ResolveClientUrl("~/js/qTipCode.js") %>"></script>

因此,这归结为:

1. writing a single user control 
2. registering the user control on .aspx content pages that will need it
3. sprinkling the .aspx content page with the user control tag whereever it is needed
4. adding the script tag to point to the qtip Javascript file 
5. ensuring that the selectors in the jQuery "match up" with the HTML markup on the page 

我希望这能帮助其他人。尝试这个我学到了很多新东西。

最新更新