问题描述
如何格式化来自 ASPX 页面中 DataBinder.Eval 语句的数据?
How can I format data coming from a DataBinder.Eval statement in an ASPX page?
例如,我想在主页中以特定格式显示新闻项目的发布日期.我正在使用 ASP.NET 2.0 Repeater 控件来显示新闻项目列表.
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
代码如下:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
有没有一种方法可以调用自定义方法,并将 DataBinder.Eval 值作为其参数(如下所示)?
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
如果是,那么我在哪里编写 GetDateInHomepageFormat 方法?我在页面后面的代码中进行了尝试,但出现了运行时错误?如果这不可能,有没有办法进行内联格式化?
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error? If this is not possible, is there a way to do inline formatting?
推荐答案
DataBinder.Eval 有一个可选的重载来提供格式:
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
格式参数是一个字符串值,使用值占位符替换语法(称为复合格式)如下:
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
这篇关于格式化 DataBinder.Eval 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!