您可以使用数据绑定表达式:
<asp:TextBox MaxLength="<%# Constant.Value %>" />
但是,这要求它位于数据绑定控件中。如果它不在中继器或类似的东西中,则需要在页面生命周期的某个时刻调用 Container.DataBind()。
或者,您可以创建一个ExpressionBuilder,它允许以下语法:
<asp:TextBox MaxLength="<%$ Constants:Value %>" />
这是一个从单个静态字典中提取的示例:
using System;
using System.Web.UI;
using System.Web.Compilation;
using System.CodeDom;
using System.Collections.Generic;
class ConstantsExpressionBuilder : ExpressionBuilder {
private static readonly Dictionary<string, object> Values =
new Dictionary<string, object>() {
{ "Value1", 12 },
{ "Value2", false },
{ "Value3", "this is a test" }
};
public override bool SupportsEvaluate { get { return true; } }
public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
string key = entry.Expression.Trim();
return GetValue(key);
}
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
CodePrimitiveExpression keyExpression = new CodePrimitiveExpression(entry.Expression.Trim());
return new CodeMethodInvokeExpression(this.GetType(), "GetValue", new CodeExpression[] { keyExpression });
}
public static object GetValue(string key) {
return Values[key];
}
}
您可以在 web.config 中注册它:
<system.web>
<compilation>
<expressionBuilders>
<add expressionPrefix="Constants" type="ConstantsExpressionBuilder" />
</expressionBuilders>
</compilation>
</system.web>
并在 ASPX 页面中调用它:
<asp:Textbox runat="server" MaxLength="<%$ Constants:Value1 %>" ReadOnly="<%$ Constants:Value2 %>" Text="<%$ Constants:Value3 %>" />
应该产生:
<input type="text" maxlength="12" readonly="false" value="this is a test" />
在 HTML 输出中。