views:

39

answers:

2

A very simple asp.net webform page.

<asp:DronDownList id="ddl" runat="server">
<asp:Button id="btn" runat="server" Text="Do nothing but post back" />

In Page_Load:

if (!IsPostBack)
{
   ListItem item = new ListItem("text1","value1");
   item.Attributes["custom"] = "CustomValue";
   ddl.Items.Add(item);
}

The html it renders:(which looks good)

<select ...>
  <option value="value1" custom="CustomValue">text1</option>
</select>

After the button is clicked, I view the source, custom="CustomValue" is gone. I know you will say "it's because you put it in a if (!IsPostBack) block". Of course everything will be ok if I remove the if statement. But why other STANDARD attributes are rendered? Since I put it in the if statement, i suppose the output will be:

<select ...></select>   // i suppose no options in it! 

Why does ASP.NET "choose" attributes?

+1  A: 

Its a trade-off. Control has to persist (non-default)value of every attribute that it supports in the view-state. So there is naturally impact on the view-state size and hence page size. Therefore, it make sense for control developers only to back most commonly used attributes into the view-state. Same has been the case here - where control developers has decided not to back custom attributes into the view-state.

VinayC
But how can I resolve this problem? I need the custom attribute.
Danny Chen
Well you can add the attribute at design time. If the value may change then add the attribute every time page runs (i.e. in post-back scenario also). If you have to do it for many times then I will suggest that you write custom controls (inherited from say drop-down list) or user controls (containing say drop-down list), add code to persist custom attributes in view-state (overriding LoadViewState and SaveViewState methods).
VinayC
A: 

ASP .NET does not save custom attribute in ViewState.

jebberwocky