Use multiple models in one view

I want to use 2 models in a single view.

Here is my index view markup:

@model IEnumerable<Enteripse_web.Models.Post>
@model PagedList.IPagedList<Enteripse_web.Models.Post>
@using Microsoft.AspNet.Identity
@using Enteripse_web.Models
@using PagedList.Mvc;
@using PagedList;
@{
    ViewBag.Title = "Posts";
}
<h1 class="post-group-heading">Post</h1>
<div class="row">

    @if (User.Identity.IsAuthenticated)
    {
        foreach (var item in Model)
        {
            <div>
                @Html.DisplayFor(x => item.Title)
            </div>
            <div>
                @Html.DisplayFor(x => item.Time)
            </div>


            <div>
                @Html.ActionLink("Details", "Details", "Posts1", new { id = item.PostId }, null)
            </div>
        }
    }
    <br />

    @Html.PagedListPager(Model, page => Url.Action("Index",
        new { page = page }))
    </tr>
    else
    {
    <h2>
        <strong>@ViewBag.Name</strong> :)
    </h2>
    }
</div>

I want to use these models:

@model IEnumerable<Enteripse_web.Models.Post>
@model PagedList.IPagedList<Enteripse_web.Models.Post>

How can I use 2 models in one view? Please let me know if you can help. <3 from Greenwich university.

Upvotes: 0

Views: 4826

Answers (2)

Berkin &#214;ztekin
Berkin &#214;ztekin

Reputation: 60

Create a third model(class) which includes both of these models and send it to your view.

Upvotes: 0

Shehryar
Shehryar

Reputation: 31

No, you cannot use 2 models in one view. One way to solve this problem is that create another view model class, and declare the properties of both models you want to use, in that one view model class. This way, you can use the view model class in your view. This will solve your problem.

Note: It is always recommended to create view model classes instead of directly interacting with the Dbcontext classes.

Upvotes: 1

Related Questions