Creating a reusable content part in MVC
I have the following block of HTML to display something, comments for instance:
<div class="comment">
...
</div>
开发者_JAVA技巧And this HTML block uses a Comment object to display the data.
I'm using Razor.
How can I create this section so I can re-use it in my other view pages, by simply passing in a comment object.
Is this a partial view?
Is this a partial view?
Yes, this looks like a good candidate for a partial view (~/Views/Shared/_Comment.cshtml
):
@model CommentViewModel
<div class="comment">
...
</div>
and then when you need to use it somewhere:
@model SomeViewModel
...
@Html.Partial("_Comment", Model.Comment)
Another possibility is to use a display template (~/Views/Shared/DisplayTemplates/CommentViewModel.cshtml
):
@model CommentViewModel
<div class="comment">
...
</div>
and then when you need to use it somewhere:
@model SomeViewModel
...
@Html.DisplayFor(x => x.Comment) // the Comment property is of type CommentViewModel
and yet another possibility is to use the Html.Action and Html.RenderAction helpers.
So as you can see ASP.NET MVC offers different ways of creating reusable parts.
精彩评论