7

In the following example,

<uc1:MyUserControl>

   <p>this is html</p>

</uc1:MyUserControl>

How do I access "<p>this is html</p>" as a string within MyUserControl so that I might inject it into the response?

I'm not talking about passing in a string parameter like <uc1:MyUserControl myparameter="<p>this is html</p>" />, but how do I access true multi-lined intellisensed HTML markup either between the opening and closing tags or by some other mechanism such as a <MessageTemplate> tag.

Bonus points for a solution that works in ASP.NET MVC 3!

EDIT:

Thanks to StriplingWarrior and this link as the missing puzzle piece, magic was made:

So, in any view:

<%@ Register src="../../Shared/Ribbon.ascx" tagname="Ribbon" tagprefix="uc1" %>
...
<uc1:Ribbon ID="Ribbon" runat="server">
    <Content>
    Hello world! I am <b>pure html</b> being passed into a UserControl!
    </Content>
</uc1:Ribbon>

In Ribbon.ascx:

<%@ Control Language="C#" CodeBehind="Ribbon.ascx.cs" Inherits="NunYourBeezwax.Views.Shared.Ribbon" %>
<table>
    <tr>
        <td>I am reusable stuff that wraps around dynamic content</td>
        <td><%= this.Content %></td>
        <td>And I am stuff too</td>
    </tr>
</table>

And finally, in Ribbon.ascx.cs (Need to manually add in MVC)

using System.Web.Mvc;
using System.Web.UI;

namespace NunYourBeezwax.Views.Shared
{
    [ParseChildren(true, "Content")]
    public class Ribbon : ViewUserControl
    {
        [PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
        public string Content { get; set; }
    }
}

Will Render as:

<table>
    <tr>
        <td>I am reusable stuff that wraps around dynamic content</td>
        <td>Hello world! I am <p>pure html<p> being passed into a UserControl!</td>
        <td>And I am stuff too</td>
    </tr>
</table>
Community
  • 1
  • 1
Levitikon
  • 7,749
  • 9
  • 56
  • 74
  • Does this only work in MVC? I'm trying to get something similar to work in a non MVC environment to no avail, not sure which part is MVC specific? It would be cool if you created an answer that has your solution, or updated the accepted answer to include your code. – Will Lanni Dec 11 '17 at 19:49

1 Answers1

3

In typical WebForms controls, the HTML will be automatically put into a Literal control in MyUserControl's Controls collection. Controls with template properties work a little differently, but you may still be able to access this in a similar way through the property whose name you're using (e.g. MessageTemplate).

MVC works totally differently, and I don't know if there's a way to do what you're asking there. You may want to consider using javascript to analyze what actually gets rendered client-side if it doesn't work for you.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315