Pierre Lebon Pierre Lebon - 28 days ago 10x
C# Question

Creating User HTML Control

I want to create a Custom Html Control.

In the ASPX :

<custom:Message runat="server" ID=""
Type="" // { "Tip", "Note", "Important", "Warning" , "Caution" }
Visible="" />

The Html generated :

<div class="fixedClass customClass">
<span class="label">caution</span><hr>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ipsum lectus, cursus id rutrum vel
, feugiat eget leo. <strong>Cras suscipit urna vel</strong> nibh placerat vestibulum.


Type is for the customClass of the main div.

Label is the text in the
<span class="label">

Text is the text in the


You can use ASP.NET User Controls for this. It's a very common, well-used feature of ASP.NET Forms. I'm surprised your research didn't turn it up already :-)

Anyway, you can create a new User Control when you go to "Add New Item" in Visual Studio. Choose "Web User Control" from the list of templates. This will create a file with a .ascx extension - this is your user control. In it you can add any HTML markup you want, javascript, and other .NET controls (and even other user controls). It also has code-behind which can respond to events etc. in the same way as a full page.

Once that's created and included in your project, you can use in your main aspx pages. This is in two parts - first add a directive to register the control, and then you can add a tag to use the control in the same way as the built-in controls.

<%@ Register TagPrefix="uc" TagName="myControl" Src="~/Controls/myControl.ascx" %>
<uc:myControl id="ctrl1" runat="server"/>

If you want to have attributes on the control (e.g. "Label" and "Text" as you discussed, define public properties in the code-behind of the control:

public string Label { get; set; }
public string Text { get; set; }

Then obviously somewhere in the code behind you can use these values to populate the UI or whatever.

To use them in the markup:

<uc:myControl id="ctrl1" runat="server" Label="TestLabel" Text="TestText" />

Alternatively you can populate them from the code-behind of the page where you're using the control, just like any public property of an object.

More info can be found here: https://msdn.microsoft.com/en-us/library/wt3k2fyw.aspx (how to create user controls) and https://msdn.microsoft.com/en-us/library/sbz9etab.aspx (how to include them in your page)