You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何格式化含日期的回发标题(优先Linq和C#)及ListView按钮PostBackUrl问题

解决方案:日期格式化与ListView按钮PostBackUrl问题

一、修复ListView中Button的PostBackUrl无效问题

你遇到的PostBackUrl绑定失效,是因为ASP.NET不支持在属性值里直接嵌套Eval表达式拼接字符串。可以通过两种方式解决:

方法1:用DataBinder.Eval拼接完整URL

修改Button的PostBackUrl属性,通过DataBinder.Eval生成编码后的完整URL:

<asp:Button ID="Btn3" runat="server" 
    Text='<%# Eval("BkTime3", "{0: hh tt}")%>'
    PostBackUrl='<%# string.Format("~/contact/VidLink.aspx?Topic={0}", 
        Server.UrlEncode(DataBinder.Eval(Container.DataItem, "BkTime3", "{0: dddd, dd MMMM, hh tt}"))) %>' />

添加Server.UrlEncode是为了避免日期里的空格、逗号等特殊字符破坏URL结构。

方法2:在ListView的ItemDataBound事件中设置属性

利用ListView的ItemDataBound事件,在后台代码中找到按钮并设置PostBackUrl:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem dataItem = e.Item as ListViewDataItem;
        DateTime bkTime3 = (DateTime)DataBinder.Eval(dataItem.DataItem, "BkTime3");
        string formattedDate = bkTime3.ToString("dddd, dd MMMM, hh tt");
        
        Button btn3 = e.Item.FindControl("Btn3") as Button;
        if (btn3 != null)
        {
            btn3.PostBackUrl = $"~/contact/VidLink.aspx?Topic={Server.UrlEncode(formattedDate)}";
        }
    }
}

同时要在ListView标签上绑定事件:

<asp:ListView ID="ListView1" runat="server" OnItemDataBound="ListView1_ItemDataBound">
    <!-- 模板内容 -->
</asp:ListView>

二、基于LINQ的日期格式化实现

如果数据源是可查询集合,可直接在LINQ查询中完成日期格式化,简化页面绑定逻辑:

LINQ to Objects场景

var formattedData = originalDataSource.Select(item => new 
{
    BkTime3 = item.BkTime3,
    ShortTimeText = item.BkTime3.ToString("hh tt"),
    FullDateTopic = item.BkTime3.ToString("dddd, dd MMMM, hh tt")
}).ToList();

ListView1.DataSource = formattedData;
ListView1.DataBind();

页面绑定直接使用预格式化字段:

<asp:Button ID="Btn3" runat="server" 
    Text='<%# Eval("ShortTimeText")%>'
    PostBackUrl='<%# $"~/contact/VidLink.aspx?Topic={Server.UrlEncode(Eval("FullDateTopic").ToString())}" %>' />

LINQ to SQL/EF场景

ORM数据源中直接用ToString会报错,需先转为内存集合再格式化:

var formattedData = dbContext.Bookings
    .Where(b => b.Status == "Available")
    .AsEnumerable()
    .Select(b => new 
    {
        BkTime3 = b.BkTime3,
        ShortTimeText = b.BkTime3.ToString("hh tt"),
        FullDateTopic = b.BkTime3.ToString("dddd, dd MMMM, hh tt")
    }).ToList();

内容的提问来源于stack exchange,提问作者Gerry H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:22:47