How to force an ASP.NET server element to use an inline code block as a property value?

I have a custom server control with a Title property. When using the control, I would like to set the title value on the aspx page as follows:

<cc1:customControl runat="server" Title='<%= PagePropertyValue%>' > more content </cc1:customControl> 

However, when I do this, I get the exact String <% = PagePropertyValue%>, and not the value of the property that I would like to see.

So, try an expression for data binding (as suggested below). I don't get a string literal that looked bad, but nothing works for me either.

 <cc1:customControl runat="server" Title='<%# PagePropertyValue%>' > more content </cc1:customControl> 

What do I need to do for my user control in order to use this value? Or is there something I need to do on the page.

+7
servercontrols web-controls
source share
5 answers

You can not. <% =%> will write the line directly to the response stream that occurs after the server control is created. See this post for an explanation.

So its either codebehind or <% # + data binding, as Zachary suggests.

+7
source share

As a continuation of my own question, I found that I really wanted to use ASP.NET expressions using the <% $ syntax, because what I wanted to do was put in localized content.

This can be done, apparently, without additional server-side processing.

 <cc1:customControl runat="server" Title='<%$ Resouces: ResourceFile, ContentKey %>' > more content and controls </cc1:customControl> 

This works great.

+2
source share

Try using data binding syntax: <%# PagePropertyValue %>

+1
source share

In order for the value of the binding property to work correctly, as suggested, you will have this in the aspx or ascx file:

 <cc1:customControl runat="server" Title='<%# PagePropertyValue %>' > more content </cc1:customControl> 

Then you will need to actually bind the data on your page, which you need to add to the code behind the file (C # code)

 protected void Page_Load(object sender, EventArgs e) { DataBind(); } 

This way it will bind the data in your ascx or aspx file.

+1
source share

Note that this is specific to attribute management. When using external control attributes <% = syntax meaning anywhere else on the page, the syntax works as expected. So this <% = GetCapitalUserName ()%> will call the correct method and produce the result of the call on the page.

0
source share

All Articles