Blankman
Blankman

Reputation: 267330

Creating a reusable content part in MVC

I have the following block of HTML to display something, comments for instance:

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

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?

Upvotes: 2

Views: 1357

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

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.

Upvotes: 4

Related Questions