views:

698

answers:

2

So, I've got an ASP drop down list (this is .net 2.0). I'm binding it with data. Basically, when the page loads and it's not a post back we'll fetch record data, bind all the drop downs, and set them to their appropriate values (strictly speaking we: initialize page with basic set of data from DB, bind drop downs from DB, fetch actual record data from DB, set drown downs to appropriate settings at this time). What I want to do is selectively style the list options. So the database returns 3 items: ID, Text, and a flag indicating whether I the record is "active" (and I'll style appropriately). It's easy enough to do and I've done it.

My problem is what happens when a form submission is halted. We have slightly extended the Page class and created an AddError() method, which will create a list of errors from failed business rule checks and then display them in a ValidationSummary. It works something like this, in the submit button's click event:

CheckBizRules();

if(Page.IsValid)
{
    SaveData();
}

If any business rule check fails, the Page will not be valid. The problem is, when the page re-renders (viewsate is enabled, but no data is rebound) my beautiful conditional styling is now sadly gone, off to live in the land of the missing socks. I need to preserve it.

I was hoping to avoid another DB call here (e.g. getting the list data back from the DB again if the page isn't valid, just for purposes of re-styling the list). But it's not the end of the world if that's my course of action. I was hoping someone might have an alternative suggestion.

I couldn't think of how to phrase this question better, if anyone has any suggestions or needs clarification don't hesitate to get it, by force if need be. ;)

A: 

Well, I couldn't come up with anything except to go to the database to re-retrieve my list data when the Page was not valid, and re-style the control.

peacedog
A: 

I'm not sure I completelly understand what kind of styling you apply to your drop-down items, but it seems this style is something that the control does not preserve accross postbacks. Usually this kind of info will therefore need to be saved in the ViewState. I see two options (other than re-loading from DB):

First method: Create your own drop-down control that inherits from DropDownList. Then save styling data in the control's ViewState bag when styling the items:

public void SetItemActive(ListItem item)
       {
         ViewState[item.Value] = "active";           
        }

then override the OnRender

protected override void Render(HtmlTextWriter writer)
{

   ....

   foreach(ListItem item in Items)
   {
    if ( ViewState[item.Value] == "active")
    { 
            ** RenderActiveItem **
    }
    else 
    {
            ** RenderNormalItem **

    }

}

Second method: is to save the active ID's in the Page's ViewState then re-style the dropdown on each postback using the data from the ViewState rather than from the DB

Radu094