在我的模板中,我有这些重复的内容块,我想抽象到一个组件:
<header class="Component-header"> <!-- Some content here is always the same --> <!-- And some content is different for each use --> </header> <div class="Component-body"> <!-- Some content here is always the same --> <!-- And some content is different for each use --> </div> <footer class="Component-footer"> <!-- Some content here is always the same --> <!-- And some content is different for each use --> </footer>
通常我会使用剃刀局部视图,并传递一些变量.但是在这种情况下,这意味着将大块的html作为变量传递,这似乎并不明智.
我发现这篇文章:http://www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html,它解释了如何创建块助手.它更接近我正在尝试做的事情,但它仍然需要我将html定义为一个字符串,这不是我想要的(因为html的数量足以让它变得不可维护).
根据我的理解,我也不能使用布局,因为组件在一个页面上多次出现.所以我的问题是:如何将上面的模式抽象为单个可重用组件,我可以在页面上重用它,它接受多个html区域并接受变量?
解决方法
那么对我有用的是使用剃须刀@helper.下面的代码位于App_Code中,您可以在其中创建文件YourComponentName.cshtml.在该文件中使用以下标记:
@using System.Web.Mvc; @helper Render( ViewContext context,string title = "Default title",Func<object,object> header = null,object> content = null,object> footer = null ) { <header class="Component-header"> <!-- Some content here is always the same --> <h3>@title</h3> @if (header != null) { @header.DynamicInvoke(context); } </header> <div class="Component-content"> <!-- Some content here is always the same --> @if (content != null) { @content.DynamicInvoke(context); } </div> <footer class="Component-footer"> <!-- Some content here is always the same --> @if (footer != null) { @footer.DynamicInvoke(context); } </footer> }
然后,您可以使用模板中的组件:
@YourComponentName.Render( ViewContext,title: "Title",header: @<p>Markup for the header</p>,content: @<p>The content</p>,footer: @<p>Markup for the footer</p> )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。