このコード:
<asp:TextBox runat="server" MaxLength="<%=Settings.UsernameMaxLength %>" ID="Username"/>
パーサー エラーをスローします。
コードビハインドを使用せずに、これと同様の方法でプロパティを設定することは可能ですか?
いいえ、できません。構文<%= some code here %>
は、サーバー側のコントロールでは使用できません。を使用できますが<%# some code here %>
、データバインディングの場合のみ、またはコードビハインドでこのプロパティを設定するだけですPage_Load
。
protected void Page_Load(object source, EventArgs e)
{
Username.MaxLength = Settings.UsernameMaxLength;
}
これを試すと、レンダリング時にMaxLength値が設定されます。
<%
Username.MaxLength = Settings.UsernameMaxLength;
%>
<asp:TextBox runat="server" ID="Username"/>
私は(試していない)あなたも書くことができると思います:
<asp:TextBox runat="server" MaxLength="<%#Settings.UsernameMaxLength %>" ID="Username"/>
call Username.DataBind()
ただし、コードビハインドのどこかで必要になります。
ここでのパーティーには遅れましたが、とにかく行きましょう...
Expression Builder
このケースを処理するために独自に構築できます。これにより、次のような構文を使用できます。
<asp:TextBox
runat="server"
MaxLength="<%$ MySettings: UsernameMaxLength %>"
ID="Username"/>
$
サインに注意してください。
自分で作成する方法を学ぶにExpression Builder
は、この古くても関連性のあるチュートリアルを参照してください。最終的に、式ビルダーを作成するのは簡単なので、テキストの壁に怖がらせないでください。基本的には、クラスの派生とメソッドSystem.Web.Compilation.ExpressionBuilder
のオーバーライドで構成されます。GetCodeExpression
以下は非常に単純な例です (このコードの一部は、リンクされたチュートリアルから借用したものです)。
public class SettingsExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, System.Web.Compilation.ExpressionBuilderContext context)
{
// here is where the magic happens that tells the compiler
// what to do with the expression it found.
// in this case we return a CodeMethodInvokeExpression that
// makes the compiler insert a call to our custom method
// 'GetValueFromKey'
CodeExpression[] inputParams = new CodeExpression[] {
new CodePrimitiveExpression(entry.Expression.Trim()),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name)
};
return new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
this.GetType()
),
"GetValueFromKey",
inputParams
);
}
public static object GetValueFromKey(string key, Type targetType, string propertyName)
{
// here is where you take the provided key and find the corresponding value to return.
// in this trivial sample, the key itself is returned.
return key;
}
}
aspx ページで使用するには、次の場所にも登録する必要がありますweb.config
。
<configuration>
<system.web>
<compilation ...>
<expressionBuilders>
<add expressionPrefix="MySettings" type="SettingsExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
</configuration>
これは、難しいことではないことを示すためのものです。ただし、割り当てられているプロパティなどに応じて、メソッドから予想される戻り値の型を処理する方法の例を確認するために、リンク先のチュートリアルを確認してください。