开发者

Passing html markup into an ASP.NET User Control

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 p开发者_如何学JAVAassed into a UserControl!</td>
        <td>And I am stuff too</td>
    </tr>
</table>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜