在MVC中创建可重用的内容部分

时间:2011-10-08 21:21:55

标签: asp.net-mvc razor

我有以下HTML块来显示内容,例如:

<div class="comment">
...
</div>

此HTML块使用Comment对象显示数据。

我正在使用Razor。

如何创建此部分,以便我可以在其他视图页面中重复使用它,只需传入注释对象。

这是局部视图吗?

1 个答案:

答案 0 :(得分:4)

  

这是局部视图吗?

是的,这看起来像是部分视图(~/Views/Shared/_Comment.cshtml)的良好候选者:

@model CommentViewModel
<div class="comment">
    ...
</div>

然后当你需要在某个地方使用它时:

@model SomeViewModel
...
@Html.Partial("_Comment", Model.Comment)

另一种可能性是使用显示模板(~/Views/Shared/DisplayTemplates/CommentViewModel.cshtml):

@model CommentViewModel
<div class="comment">
    ...
</div>

然后当你需要在某个地方使用它时:

@model SomeViewModel
...
@Html.DisplayFor(x => x.Comment) // the Comment property is of type CommentViewModel

另一种可能性是使用Html.Action and Html.RenderAction助手。

因此,您可以看到ASP.NET MVC提供了创建可重用部件的不同方法。

相关问题