Search code examples
c#asp.netuser-controlscustom-server-controlshtmltextwriter

Custom Server Control in ASP.NET and C# -


I've got a aspx and aspx.cs file with some components. Now I want to reuse parts of that page in another page. My approach would be to pull out the duplicate part into a WebServerControl.

So before I waste more time yahoogling, is that even the right idea and if so, is there a way to use parts of the aspx file rather than doing it tediously in RenderContents with the HtmlTextWriter, WriteBeginTag, WriteAttribute and so on. That looks like a mess for complicated layout and sizeable amounts of controls.

What's the standard?


Solution

  • Depends.

    The main driving factor is that if you need to reuse your control in multiple web applications, you should go with a Custom Control (.cs in C#).

    Else, if you only intend to reuse your control in one web application, choose a User Control (.ascx).

    This MSDN article is a good starting point.

    UPDATE (since OP asked further details):

    To embed JavaScript for a custom control, a common approach is

    var initializeScript = string.Format("MyNamespace.initialize('{0}', {1});", ClientID, myScriptString);
    Attributes.Add("onmouseover", initializeScript);
    

    Suggest to write JavaScript code in a js file and not in .cs since the latter is a nightmare to maintain and debug. Hope this helps.