在以下示例中,
<uc1:MyUserControl>
<p>this is html</p>
</uc1:MyUserControl>
如何访问
"<p>this is html</p>"
作为 MyUserControl 中的字符串,以便我可以将其注入(inject)响应中?我不是在谈论传递像
<uc1:MyUserControl myparameter="<p>this is html</p>" />
这样的字符串参数。 ,但是如何在开始标签和结束标签之间或通过一些其他机制(如 <MessageTemplate>
)访问真正的多行智能 HTML 标记标签。在 ASP.NET MVC 3 中工作的解决方案的奖励积分!
编辑:
感谢 StriplingWarrior 和 this link作为缺失的拼图,魔术被创造了:
所以,在任何情况下:
<%@ 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>
在 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>
最后,在 Ribbon.ascx.cs 中(需要在 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; }
}
}
将呈现为:
<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>
最佳答案
在典型的 WebForms 控件中,HTML 会自动放入 MyUserControl 的 Controls
中的 Literal 控件中。收藏。具有模板属性的控件的工作方式略有不同,但您仍然可以通过您正在使用其名称的属性以类似的方式访问它(例如 MessageTemplate
)。
MVC 的工作方式完全不同,我不知道是否有一种方法可以满足您的要求。如果对您不起作用,您可能需要考虑使用 javascript 来分析客户端实际呈现的内容。
关于asp.net-mvc - 将 html 标记传递给 ASP.NET 用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345112/