Friday, September 12, 2008

How to decoratively set an attribute of a server-side control to some public property/value?

Have you ever tried to decoratively set an attribute of a server-side control to some public property/value defined in code-behind code (or in a Business Layer)? Here's a simple example:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs"
 Inherits="TestPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox ID="TextBox1" runat="server" Text="<%=hitest %>" />
    </div>
    </form>
</body>
</html>

And in a code-behind file:

public partial class TestPage : System.Web.UI.Page {
 
  public string hitest = "Hello";

This example doesn't work, ASP.NET engine does not process hitest and displays a text box with <%=hitest %> inside.

I know, I'm doing something stupid and show everybody that I understand nothing about ASP.NET, but here's a reasoning behind my attempts:
In our application we use AjaxControlToolkit, and in particular - MaskedEditExtender. There is a complicated WebForm with a ListView and numerous text boxes for entering phones, there were millions of MaskEditExtenders with identical masks set to @"(9{3}) 9{3}-9{4}". (The same story for emails.) I don't like clattering a code with "magic" strings and numbers, so I decided to declare constants and toplace them into our common class sitting in App_Code:

namespace CoTs.Partners.Common {
  public static class Util {
    public const string MailRegEx = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
    public const string PhoneMask = @"(9{3}) 9{3}-9{4}";
Then, I thought, I would set
<cc1:MaskedEditExtender Mask="<%#CoTs.Partners.Common.Util.PhoneMask %>"
- and voila. For some reason it worked fine for a ListView's "Edit", but bombed with an empty Mask in "Add". I started to investigate and decided that using of <%# is probably incorrect, because <%# implies data binding. But, as I said, <%= doesn't work either. Sure, I can assign values to Maks properties programmatically in code-behind file, but it sounds crazy, given the fact that MaskEditExtender controls are scattered inside many other controls in a complicated page.

So, again: is there a way to decoratively set an attribute of a server-side control to some public property/value (defined in code-behind code or in a Business Layer)?
Suprizingly, I couldn't find any information on a Web....