c# – 如何在ASP.NET MVC 5中抽象这个重复模式?
发布时间:2020-12-15 22:30:06 所属栏目:百科 来源:网络整理
导读:在我的模板中,我有这些重复的内容块,我想抽象到一个组件: header class="Component-header" !-- Some content here is always the same -- !-- And some content is different for each use --/headerdiv class="Component-body" !-- Some content here is
在我的模板中,我有这些重复的内容块,我想抽象到一个组件:
<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> ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |