5

I have a web control that looks like this

public class Foo : WebControl
{
  [Bindable(true)]
  [Category("Default")]
  [DefaultValue("")]
  [Localizable(true)]
  public string Bar { get; set; }

  protected override void Render(HtmlTextWriter output)
  {
    output.WriteLine(Bar);
  }
}

I want to put this webcontrol in my aspx page like so:

<cc1:Foo Bar="<%= Fa.La.La %>/otherstuff" runat="server" />

(obviously this code is simplified to show the problem)

In my Render method the variable Fa.La.La is not evaluated. It's coming in as the raw text "<%= Fa.La.La %>" How do I evaluate it?

I'm not particular how the variables are passed in. If the variables can be evaluated if they are passed in as <%# ... %>, that works fine. The point is I have some server-side variables I want evaluated before/while my Render() method is called.

The only thing I can think of is to use a regex to grab the contents of <%= ... %> and use reflection or something, but there has to be a more elegant way to do this.

This question is pretty similar to using server variables in a href <%= xx %> with runat=server, but it's not exactly the same since none of the answers there were useful.

Community
  • 1
  • 1
mhenry1384
  • 7,538
  • 5
  • 55
  • 74
  • Try using this NOTE single quote and double quote difference. I hope it may solve the issue – Moons Aug 13 '12 at 04:24

2 Answers2

6

Well, first you should be clear to diff between both tags. here are some points i have read and used practically..

  • The <%= expressions are evaluated at render time
  • The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
  • <%# expressions can be used as properties in server-side controls.<%= expressions cannot.

read more it on MSDN Blog

Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
3

You should have to use binding expression <%# expr %>.

<cc1:Foo Bar='<%# String.Concat(Fa.La.La,"/otherstuff")%>' runat="server" /> 

and call DataBind() method in code-behind.

public void page_load()
{
  DataBind();
}
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 2
    To expand on this answer, you can't do something like: Bar="<%# Fa.La.La %>/otherstuff" It just gets rendered literally. The databinding expression has to be the only thing in the attribute, e.g., Bar='<%# String.Concat(Fa.La.La, "/otherstuff") %>' Furthermore, the outside quotes should be single-quotes and the inside quotes should be double-quotes (assuming C#, anyway). – mhenry1384 Aug 13 '12 at 05:52