データバインディング式を使用できます。
<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出力で。