在资源中的内联ASP.NET表达式中应用格式化

前端开发 2026-07-09

我在ASP.NET中使用内联表达式构建器,如下所示:

<asp:Label ID="Label1" runat="server" Text="<%$ Resources: Labels, MyText %>" />

但我希望能够像数据绑定中那样对其进行格式化

<asp:Label ID="Label1" runat="server" Text='<%# Eval("MyText", "This is {0}") %>' />

或者

<asp:Label ID="Label1" runat="server" Text='<% = String.Format("This is {0}", Resources.Labels.MyText) %>' />

我可以通过不使用 Text 属性来实现,

<asp:Label ID="Label1" runat="server"><% = String.Format("This is {0}", Resources.Labels.MyText) %></asp:Label>

但在超链接控件的 NavigateUrl 中就做不到。

<asp:HyperLink ID="Hyperlink1" runat="server" NavigateUrl='<% = String.Format("/{0}/{1}", Resources.URLs.Language, Resources.URLs.MyURL) %>'><% = String.Format("This is a hyperlink with custom URL and text: {0}", Resources.Labels.MyText) %><asp:HyperLink>

还有什么选项?

解决方案

还有什么选项?

除了下面的code-behind使用方式外,将没有其他选项:

.aspx.cs (code-behind):

public partial class WebForm62 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = String.Format("This is {0}", "MyText");
        Hyperlink1.NavigateUrl = String.Format("/{0}/{1}", "en", "MyURL");
    }
}

.aspx

<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:HyperLink ID="Hyperlink1" runat="server">
    <% = String.Format("This is a hyperlink with custom URL and text: {0}", "xxx") %>
</asp:HyperLink>

生成的HTML:

<span id="Label1">This is MyText</span>
<br />
<a id="Hyperlink1" href="/en/MyURL">This is a hyperlink with custom URL and text: xxx</a>

你应该知道为什么不能使用你所参考的微软文档中所描述的用于为服务器控件设置属性的 <%= ... %> 显示表达式吗?<%= ... %> 将被视为字符串。

.aspx

<asp:Label ID="Label1" runat="server" 
    Text='<% = String.Format("This is {0}", Resources.Labels.MyText) %>'></asp:Label>
<br />
<asp:HyperLink ID="Hyperlink1" runat="server" 
    NavigateUrl='<% = String.Format("/{0}/{1}", Resources.URLs.Language, Resources.URLs.MyURL) %>'>
    <% = String.Format("This is a hyperlink with custom URL and text: {0}", "xxx") %>
</asp:HyperLink>

结果将生成以下HTML:

<span id="Label1"><% = String.Format("This is {0}", Resources.Labels.MyText) %></span>
<br />
<a id="Hyperlink1" 
  href="&lt;%%20=%20String.Format(&quot;/{0}/{1}&quot;,%20Resources.URLs.Language,%20Resources.URLs.MyURL)%20%>">
  This is a hyperlink with custom URL and text: xxx
</a>

如果你因为某些原因不能使用code-behind,必须使用 <%= ... %> 展示表达式,请说明原因。很可能在不使用内联 <%= ... %> 展示表达式的情况下找到可行的解决方案。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章