Friday, April 20, 2007

MVC and Building User controls (Specifically .Net ASCX files).

MVC and Building User control's (Specifically .Net ASCX files).

User Controls are a common way to develop reusable UI components that use a common layout or have common generic functionality. Unfortunately I so often see these controls being developed, in my mind, incorrectly. User controls should generally be dumb. They should know very little of the out side world (except of course of the namespaces they inherit from and maybe utility classes that perform common public static encapsulated method calls). Think text boxes, drop down lists etc. These don't know about your business objects! You passed in and retrieve properties from them. They may do some basic processing however this is generic. They should certainly never call or run business logic or know about services. So how do we use User Controls to run common logic? On the user control there should be publicly visible properties. This is usually a given. There can also be methods and events. Often I call a PopulateControl(Type type) (which is a public void Method) that takes in a control specific DTO (or collection of DTO's). Usually this merely passes each of the properties in the DTO to the properties in the Control. Right, so data is in the control, how do we do stuff with it? The page load may have some generic code, but avoid adding smarts that are too specific. How about passing data back to the parent? Either retrieve the data from a MyDto read only property the does the exact opposite of the populate control returning a DTO or create a custom event eg Save and pass a delegate into the control. Yes this mean code stays on the page. So?? If it commonly called create a class that does all the leg work for you that all page can call. This then follows the MVC pattern and separates the visual aspect from the Data aspects

Question: why do you use PopulateControl(Type type) and RetrieveDTO() and not properties? Answer: I am of the opinion that a property should never be able to throw an exception or call code that can throw an exception. If you are confident that this can not happen then, sure, use the property approach. However, if there is functionality that may cause an exception, then use the method approach. I wouldn't expect people to strictly follow this, this is just my preference.

Question: When to use Delegates? Answer: When it is obvious that this control does something, like its is a control that has customer details for adding or editing then a save delete and cancel buttons may be appropriate. Control of what is done on the User Control (usually the page) with the event (ie EditCustomer_OnSave()) means that page can pass in the correct logic or call to the manager of logic as a delegate. Obviously this means exposing something to apply the delegate to, such as an event!

I am more than happy for feed back on this. I want to do better code, you may be able to help!

No comments: