How to communicate between ASP.net custom controls
I'm using two custom controls. One gathers the criteria for a search, and the other displays a list. These two controls need to remain seperate for 开发者_Go百科the time being.
What is the best method of transfering data from the search control, to the list control?
I'm thinking of ViewState, Session or wrapping both within a UpdatePanel and using custom events??
Maybe you can create a delegate and an event to pass a list of searchvalues? This way you can easily add another or multiple display controls in case that ever becomes necessary.
Note that this is just some quick sample code that should be optimized/improved.
public class SearchControl
{
public delegate void SearchEventHandler(object sender, Dictionary<string, string> SearchValues);
public event SearchEventHandler OnSearch;
public SearchControl()
{
btnSearch.Click += new EventHandler(Search);
}
protected void Search(object sender, EventArgs e)
{
if (OnSearch != null)
{
Dictionary<string, string> searchValues = new Dictionary<string, string>();
searchValues.Add("name", "John");
searchValues.Add("age", "24");
OnSearch(this, searchValues);
}
}
}
public class DisplayControl
{
public void ShowResults(Dictionary<string, string> SearchValues)
{
// Some logic here...
}
}
public class YourWebPage
{
SearchControl searcher = new SearchControl();
DisplayControl displayer = new DisplayControl();
public YourWebPage()
{
searcher.OnSearch += new SearchControl.SearchEventHandler(searcher_OnSearch);
}
public void searcher_OnSearch(object sender, Dictionary<string, string> SearchValues)
{
displayer.ShowResults(SearchValues);
}
}
Expose a public property of the type of data you have, then a public method to bind the data to your list
If the controls are separate, they should probably not be communicating directly. After all - most other .NET controls don't communicate directly either. I can only think of two exceptions - child/parent controls sometimes communicate basic information; and data-bound controls sometimes communicate directly with a DataSource. But that's largely it.
If you need to hook up two adjacent controls then the "normal" way of doing it is that their container takes care of it. Like, if a button click affects the text on the label, it is the Page (container for them both) that handles the Click event and sets the Text property.
Alternatively you could also give your ListControl a property called FindControl and assign it in Page_Init or something. But if the coupling is so tight, you might wonder if it would not be better to merge the controls too.
It depends on where the search is performed and what data is transferred between the controls. In my opinion, it is probably best to just pass the criteria to the page and have the page run the search bind them to the list control to display the results.
精彩评论