ASP.NET WebForms:为强类型ListView字段设置格式文本

时间:2014-03-26 14:00:33

标签: asp.net

我是以下标记:

<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
    <listiview tags>
        <asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
            {0:C}",Item.Amount) %>"
    </listiview tags>
</asp:ListView>

在给定的示例中,我正在尝试将货币格式应用于由标签呈现的文本,但我是在为文本控件实现此功能之后(标签,文字,文本框等)。问题是以上产生以下服务器错误:

  

“Analizer Error Mesage:无效的服务器标记”

如果我尝试使用以下内容,结果相同:

<asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
    {0:C}",Item.Amount.ToString("C")) %>"

另一种方法,这次我得到运行时异常:

<%# String.Format("{0:C}", Eval(Item.Amount.ToString() )) %>
  

DataBinding:'System.Data.Entity.DynamicProxies ...不包含   名为'500000,00'的财产。

我尝试过的另一种方法是形成实体的属性:

[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Amount { get; set; }

这不会产生任何错误但是没有形成文本,标签只是渲染没有格式的值

唯一可行的方法是使用旧方式数据绑定:

<%# String.Format("{0:C}", Eval("Amount")) %>

但是,如果我要对Webforms使用强类型绑定,我不想再使用字符串来解析属性值: 我认为这一定很容易,任何想法?

1 个答案:

答案 0 :(得分:3)

尝试从双引号切换到text属性的单引号,当前使用它的方式提前结束字符串,因此text属性实际上只是"<%#:string.Format("

<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
    <listiview tags>
        <asp:Label ID="lblDebtAmount" runat="server" Text='<%#:string.Format("
            {0:C}",Item.Amount) %>'
    </listiview tags>
</asp:ListView>
相关问题