Asp.Net Custom Server Control: PostBack handling

Posted on

Problem

I wrote a custom server control. The data in it can be manipulated on the client and the changes will be written into the hidden field. The data represents a property of the control and should be retrieved on a postback. I achieved this by using the value changed event to set the property and all its dependencies.
Is this a good a way to do this? Or can this code be improved?

public class Control : CompositeControl {

  private bool mProperty;
  private HiddenField hiddenField;


  public virtual bool Property {
    get {
      return mProperty;
    }
    set {
      mProperty = value;
      if (contentPanel != null) contentPanel.Visible = value;
      if (hiddenField != null && hiddenField.Value != value.ToString().ToLower()) hiddenField.Value = value.ToString().ToLower();
    }
  }
  protected override void CreateChildControls() {
    Controls.Clear();
    CreateControlHierarchy();
    ClearChildViewState();
  }
  protected virtual void CreateControlHierarchy() {
    CreateHiddenField();
    CreateContent();
  }

  protected virtual void CreateHiddenField() {
    hiddenField = new HiddenField();
    hiddenField.ID = "hiddenField";
    hiddenField.Value = Property.ToString().ToLower();
    hiddenField.ValueChanged += hiddenField_ValueChanged;
    Controls.Add(hiddenField);
  }  
  protected virtual void CreateContent() {
    contentPanel = new Panel();
    contentPanel.ID = "content";
    contentPanel.Vsiible = Property;
    Controls.Add(contentPanel);
  }
  void hiddenField_ValueChanged(object sender, EventArgs e) {
    Property = Convert.ToBoolean(hiddenField.Value);
  }
  protected override void OnInit(EventArgs e) {
    EnsureChildControls();
    base.OnInit(e);
  }
}

Solution

You can just expose hiddenField.Value in the property.

public bool Property
{
    get
    {
        EnsureChildControls();
        return Convert.ToBoolean(hiddenField.Value);
    }
    set
    {
        EnsureChildControls();
        hiddenField.Value = value.ToString();
    }
}

Property will expose the current value on postback by it self.

You could also expose an event on your control that you refire in the ValueChanged event of the hidden field.

public event EventHandler PropertyChanged;

...

void hiddenField_ValueChanged(object sender, EventArgs e)
{
    ContentPanel.Visible = Property;
    if (PropertyChanged != null) PropertyChanged(this, EventArgs.Empty);
}

I moved the visibility here since it’s more related to the value changing than the property itself.

Leave a Reply

Your email address will not be published. Required fields are marked *