tags:

views:

24

answers:

2

I have some logic that loops and adds a new Panel control to another control:

for (int segmentIndex = 0; segmentIndex < segments.Length; ++segmentIndex)
{
    holder.Controls.Add(new Panel() { Width = Unit.Percentage(segments[segmentIndex] / segmentsSum * 100), CssClass = String.Format("segment segment-{0}", segmentIndex) });
}
container.Controls.Add(holder);  

This works great, but there are a few values that I need to store on each panel within the loop. I need to be able to access these values in both c# and javascript, once the control is rendered on the page. What would be the best way to achieve this? I've used the Tag property before on some controls, but a Panel doesn't have one.

Thanks so much

+1  A: 

It sounds like you need to add markup inside of the Panel, is that correct? If so, you can add a control to the Panel control's Controls collection, such as a Label or a LiteralControl.

The following (non-tested) code illustrates this point:

for (int segmentIndex = 0; segmentIndex < segments.Length; ++segmentIndex)
{
    var p = new Panel() { ... };

    var innerContent = new LiteralControl("<p>Hello, World!</p>");

    p.Controls.Add(innerContent);

    holder.Controls.Add(p);
}
container.Controls.Add(holder);  

Alternatively, instead of a LiteralControl you could add a Label, a Button... whatever you need.

Scott Mitchell
I don't think a LiteralControl can be accessed from the server?
subt13
Your point is well taken, however. I need the smallest footprint available to store these values.
subt13
@sub13: You can certainly use a LiteralControl. See http://msdn.microsoft.com/en-us/library/system.web.ui.literalcontrol.aspx. And the LiteralControl can use the smallest footprint, as you can put precisely what you want in the LiteralControl's Text property (which is what gets emited when rendered).
Scott Mitchell
A: 

Add a HiddenField to your panel. It will render in HTML as <input type="hidden" /> so it's invisible, accessible for your server code and also for your javascript.

LiteralControl innerContent = new LiteralControl("<p>Hello, World!</p>");
HiddenField hiddenContent = new HiddenField() { ID = "hiddenContent", Value = "My hidden content" };
p.Controls.Add(innerContent);
p.Controls.Add(hiddenContent);
Tom Vervoort
Since I have multiple values would you recommend multiple HiddenFields or a single HiddenField with the values concatenated?
subt13
It doesn't really matter as long as it gets the job done. :-) Maybe creating multiple hiddenfields is easier if you want to access the data in javascript. It can also make your code easier to read and understand.
Tom Vervoort