5 html c# asp.net-mvc razor asp.net-mvc-5
在我的模板中,我有这些重复的内容块,我想抽象为一个组件:
<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>
Run Code Online (Sandbox Code Playgroud)
通常,我会为此使用剃刀局部视图,并将一些变量传递给它。但是,在这种情况下,这意味着将大量的html作为变量传递,这似乎并不明智。
我发现了这篇文章:http : //www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html,其中介绍了如何创建块帮助器。它与我要执行的操作有点接近,但是仍然需要我将html定义为字符串,这不是我想要的(因为html的数量足够大,以致于无法维护)。
据我了解,我也不能为此使用布局,因为组件在一页上出现多次。所以我的问题是:如何将上面的模式抽象为一个可重用的组件,我可以在一个页面上重用该组件,该页面接受html的多个区域并接受变量?
小智 2
所以对我有用的是使用剃须刀@helper。下面的代码位于您App_Code创建文件的位置YourComponentName.cshtml。在该文件中使用以下标记:
@using System.Web.Mvc;
@helper Render(
ViewContext context,
string title = "Default title",
Func<object, object> header = null,
Func<object, object> content = null,
Func<object, 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>
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在模板中使用该组件:
@YourComponentName.Render(
ViewContext,
title: "Title",
header: @<p>Markup for the header</p>,
content: @<p>The content</p>,
footer: @<p>Markup for the footer</p>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
354 次 |
| 最近记录: |