C# 如何在ASP.NET MVC 5中抽象这个重复模式?

C# 如何在ASP.NET MVC 5中抽象这个重复模式?,c#,html,asp.net-mvc,razor,asp.net-mvc-5,C#,Html,Asp.net Mvc,Razor,Asp.net Mvc 5,在我的模板中,我有这些重复的内容块,我想将其抽象为单个组件: 通常我会使用razor局部视图,并向其传递一些变量。然而,在这种情况下,这意味着将大块html作为变量传递,这似乎并不明智 我发现了这篇文章:,它解释了如何创建块帮助器。这有点接近我要做的,但它仍然要求我将html定义为字符串,这不是我想要的(因为html的数量太大,以至于无法维护) 据我所知,我也不能为此使用布局,因为组件在一个页面上出现多次。因此,我的问题是:如何将上述模式抽象为一个可重用组件,我可以在一个页面上重用该组件,该

在我的模板中,我有这些重复的内容块,我想将其抽象为单个组件:


通常我会使用razor局部视图,并向其传递一些变量。然而,在这种情况下,这意味着将大块html作为变量传递,这似乎并不明智

我发现了这篇文章:,它解释了如何创建块帮助器。这有点接近我要做的,但它仍然要求我将html定义为字符串,这不是我想要的(因为html的数量太大,以至于无法维护)


据我所知,我也不能为此使用布局,因为组件在一个页面上出现多次。因此,我的问题是:如何将上述模式抽象为一个可重用组件,我可以在一个页面上重用该组件,该页面可以接受多个html区域并接受变量?

因此,对我有效的方法是使用razor
@helper
。下面的代码放在您的
应用程序中,您可以在其中创建文件
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>
}
@使用System.Web.Mvc;
@辅助渲染(
ViewContext上下文,
string title=“默认标题”,
Func header=null,
Func content=null,
Func footer=null
)
{
@头衔
@if(header!=null){@header.DynamicInvoke(context);}
@如果(content!=null){@content.DynamicInvoke(context);}
@如果(footer!=null){@footer.DynamicInvoke(context);}
}
然后,您可以将模板中的组件用于:

  @YourComponentName.Render(
    ViewContext,
    title: "Title",
    header: @<p>Markup for the header</p>,
    content: @<p>The content</p>,
    footer: @<p>Markup for the footer</p>
  )
@YourComponentName.Render(
ViewContext,
标题:“标题”,
标题:@标题的标记,
内容:@内容

, 页脚:@页脚的标记

)
在功能上,我想要的类似于emberjs处理组件的方式:,但我想要的是多个
产生
区域。你也可以查找前端框架,这些框架将这个问题从你身边抽象出来,因此你只需要处理适当的视图逻辑。框架,如Aurelia、ReactJs、AngularJS 1/2@CallumLinington您的意思是与.net mvc结合使用?不,您会发现与WebApi结合使用会更好—这与mvc相比一点也不困难