Literal content is not allowed within a UserControl

How to allow my control contains a text inside it’s tags?

<uc:My runat="server">Text</uc:My>

My control contains a complex table and I want to put Text into one of cells. How to do that?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

[PersistChildren(false)]
[ParseChildren(true, "Text")]
public partial class RequiredFieldMarker : UserControl, ITextControl
{
    [Category("Settings")]
    [PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
    public string Text
    {
        get
        {
            return lblName.Text;
        }
        set
        {
            lblName.Text = value;
        }
    }
}

Method 2

Have a property on your user control called Text, and set that like

<uc:My id="my" Text="some text" runat="server">Text</uc:My>

or server side

my.Text = "some text";

Method 3

Assuming the UC generates a table, the easiest method I can think of is this:

In the UserControl’s ascx do something like this:

<table>
  <tr>
     ....
     <td><asp:Literal runat="server" ID="ltCellContent" /></td>
     .... 
  </tr>
</table>

In the UserControl’s code behind:

public string CellContent 
{ 
  get { return ltCellContent.Text; } 
  set { ltCellContent.Text = value; } }
}

And to use it:

<uc:My runat="server" CellContent="Some content" />

Method 4

Just add one line before the class ([ParseChildren(true, “TestInnerText”)]), and add a property named “TestInnerText”. Create any control of your choice, I have created LiteralControl just to display inner html view.

“TestInnerText” – is just a temporary name I gave, you can use any property name of your choice.

Do the following change in my.aspx.cs file,

[ParseChildren(true, "TestInnerText")]
public partial class My : UserControl
{
    public string TestInnerText
    {
        set
        {
            LiteralControl lc = new LiteralControl();
            lc.Text = value;
            this.Controls.Add(lc);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x