使用元数据和/或反射来生成ASP.净工具提示



我想知道是否有一种方法可以使用元数据轻松地为标签和文本框生成工具提示。我找到了很多关于如何在ASP中做到这一点的资源。NET MVC,但不是普通的ASP.NET。我尝试过使用各种Display属性以及Description,但没有成功。有没有一种简单的方法可以让它自动化呢?

例如,当鼠标停留在生成的网页上DateSent对应的asp:Labelasp:TextBox上时,我想使用如下代码显示"Date that the application was sent"。

public class ProjectMetadata
{
    [Required(ErrorMessage = "Enter a date")]
    [Description("Date that the application was sent")]
    public object DateSent { get; set; }
    [Required(ErrorMessage = "Enter a description")]
    [StringLength(256, ErrorMessage="Description must be 256 characters or less")]
    public object Description { get; set; }
}
[MetadataType(typeof(ProjectMetadata))]
public partial class Project
{
    public DateTime DateSent { get; set; }
    public string Description { get; set; }
}

编辑请注意,目前我让ASP。. NET完成在页面上生成控件的所有工作(代码隐藏中没有完成任何工作):

<asp:TextBox ID="tbDateSent" runat="server" Text='<%# Bind("DateSent", "{0:d}") %>'/>
<asp:Label ID="LabelDateSent" runat="server" Text='<%# Eval("DateSent", "{0:d}") %>'/>

也许这是我需要添加的东西,如:ToolTip='<%# SomeExpressionHere %>' ?

如何填充。net控件?我猜是这样的:

Project project = GetProject();
// TextboxProjectName is your TextBox on your Page / UserControl
TextboxProjectDescription.Text = project.Description; 
TextboxProjectDescription.Attributes["data-tooltip"] = project.DateSent.ToShortDateString(); // Or whatever format you want

那么你会有这样的标记:

<input type="text" data-tooltip="Your date string" />

然后你可以简单地使用jQuery工具提示库来提示所有的HTML元素,其中有数据(" Tooltip ")。

编辑

试试这个:

[MetadataType(typeof(ProjectMetadata))]
public partial class Project
{
    public DateTime DateSent { get; set; }
    public string Description { get; set; }
    public string TooltipText 
    { 
       get {
           return "Date: " + DateSent.ToShortDateString(); // whatever tooltip you want
       }
       set {}
    }
}

那么你可以按要求做:

<asp:TextBox ID="tbDateSent" runat="server" Text='<%# Bind("DateSent", "{0:d}") %>'
ToolTip='<%# Bind("TooltipText") %>' />

最新更新