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

如何在ASP.NET内联表达式中格式化资源内容?

ASP.NET 资源表达式格式化解决方案

给你几个可行的方案,解决资源格式化及HyperLink控件属性赋值问题:

方案一:用数据绑定表达式配合DataBind()

数据绑定表达式(<%# %>)支持在控件属性中直接做字符串格式化,只要在后台调用DataBind()触发绑定即可。

前端代码示例:

<!-- Label控件格式化文本 -->
<asp:Label ID="Label1" runat="server" Text='<%# string.Format("This is {0}", Resources.Labels.MyText) %>' />

<!-- HyperLink控件同时格式化URL和文本 -->
<asp:HyperLink ID="Hyperlink1" runat="server" 
    NavigateUrl='<%# string.Format("/{0}/{1}", Resources.URLs.Language, Resources.URLs.MyURL) %>'
    Text='<%# string.Format("This is a hyperlink with custom URL and text: {0}", Resources.Labels.MyText) %>'>
</asp:HyperLink>

后台触发绑定:

在Page_Load事件中调用DataBind(),可以绑定整个页面或单个控件:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // 绑定整个页面的所有数据绑定表达式
        this.DataBind();
        // 或者仅绑定单个控件:Hyperlink1.DataBind();
    }
}

方案二:自定义资源表达式生成器

如果需要像内置资源表达式(<%$ Resources: ... %>)一样简洁的写法,且支持格式化,可以自定义一个表达式生成器。

1. 创建表达式生成器类

using System;
using System.Web.Compilation;
using System.Web.UI;
using System.CodeDom;

[ExpressionPrefix("FormattedResources")]
public class FormattedResourceExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        // 拆分表达式参数:资源类名、资源键、格式化字符串(支持多参数)
        string[] rawParts = entry.Expression.Split(',');
        if (rawParts.Length < 3)
            throw new ArgumentException("表达式格式应为:FormattedResources: 资源类名, 资源键, \"格式化字符串\"[, 其他资源类名, 其他资源键...]");

        // 提取格式化字符串和资源参数
        string formatString = rawParts[2].Trim().Trim('"');
        var resourceExpressions = new CodeExpression[rawParts.Length / 2];
        
        for (int i = 0; i < rawParts.Length; i += 2)
        {
            string resourceClass = rawParts[i].Trim();
            string resourceKey = rawParts[i + 1].Trim();
            
            // 生成获取资源值的代码
            resourceExpressions[i/2] = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression(typeof(Resources.ResourceManager)),
                "GetString",
                new CodePrimitiveExpression(resourceKey),
                new CodeTypeReferenceExpression(resourceClass)
            );
        }

        // 组合String.Format的调用代码
        var formatArgs = new CodeExpression[resourceExpressions.Length + 1];
        formatArgs[0] = new CodePrimitiveExpression(formatString);
        Array.Copy(resourceExpressions, 0, formatArgs, 1, resourceExpressions.Length);

        return new CodeMethodInvokeExpression(
            new CodeTypeReferenceExpression(typeof(string)),
            "Format",
            formatArgs
        );
    }
}

2. 在web.config中注册表达式生成器

<system.web>
  <compilation debug="true" targetFramework="4.8">
    <expressionBuilders>
      <add expressionPrefix="FormattedResources" type="FormattedResourceExpressionBuilder"/>
    </expressionBuilders>
  </compilation>
</system.web>

3. 前端使用示例

<!-- Label格式化文本 -->
<asp:Label ID="Label1" runat="server" Text='<%$ FormattedResources: Labels, MyText, "This is {0}" %>' />

<!-- HyperLink格式化URL(多资源参数)和文本 -->
<asp:HyperLink ID="Hyperlink1" runat="server" 
    NavigateUrl='<%$ FormattedResources: URLs, Language, "/{0}/{1}", URLs, MyURL %>'
    Text='<%$ FormattedResources: Labels, MyText, "This is a hyperlink: {0}" %>'>
</asp:HyperLink>

方案三:后台代码直接赋值

最简单直接的方式,跳过前端表达式,在后台事件中直接给控件属性赋值,适合复杂逻辑或需要动态调整的场景。

前端代码:

<asp:Label ID="Label1" runat="server" />
<asp:HyperLink ID="Hyperlink1" runat="server" />

后台赋值代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Label1.Text = string.Format("This is {0}", Resources.Labels.MyText);
        Hyperlink1.NavigateUrl = string.Format("/{0}/{1}", Resources.URLs.Language, Resources.URLs.MyURL);
        Hyperlink1.Text = string.Format("This is a hyperlink with custom URL and text: {0}", Resources.Labels.MyText);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 01:18:11