Reputation: 1432
I'm using web forms and have same text in two different blocks. HTML:
<div class="div1">
<p>My text</p>
</div>
<div class="div2">
<p>My text</p>
</div>
I have to use asp.net controls. The code I'm using
<asp:Literal runat="server" ID="lblText"></asp:Literal>
Is there any way to re-use this control for second text block instead of creating a clone of this control with another ID?
I can't use tags like <%=
for this page.
Upvotes: 1
Views: 268
Reputation: 2367
Yes, you can encapsulate asp: Literal
along with the HTML of your DIV within a UserControl
and expose theText
property.
MyText.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyText.ascx.cs" Inherits="MyText" %>
<div>
<p>
<asp:Literal runat="server" ID="lblText" />
</p>
</div>
MyText.ascx.cs:
using System.Web.UI;
public partial class MyText : UserControl
{
public string Text
{
get
{
return lblText.Text;
}
set
{
lblText.Text = value;
}
}
}
And using it in WebForm:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="MyText.ascx" tagname="MyText" tagprefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:MyText ID="uc1MyText1" runat="server" Text="My text"/>
<uc1:MyText ID="uc1MyText2" runat="server" Text="My text 2"/>
<uc1:MyText ID="uc1MyText3" runat="server" Text="My text 3"/>
</form>
</body>
</html>
Result:
Upvotes: 1