Home > Enterprise >  Use multiple models in one view
Use multiple models in one view

Time:04-21

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 >Post</h1>
<div >

    @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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related