einverne
einverne

Reputation: 6682

How to pass List model to view in MVC4?

In my HomeController I create a model.

var model = this._postService.GetPostByParams(...);
return View(model);

And I can get the model in View.

@model ShowPin.Core.Paging.PagedList<ShowPin.Core.Domain.Posts.Post>

@foreach(var item in Model){
    <li>@Html.RouteLink(item.Title, "Post", new { postId = item.Id})</li> 
}

However, in some of my view, I want several model to pass to View . How can I get It.

I have read a lot of articles but I always got errors.

Reference:

I try to use ViewData but I cannot cast my model to right type.

I try to use this way. After I create a new model class repository.

public class Repository
{
    public Repository()
    {

    }
    public IPagedList<Post> cat1 { get;set; }
    public IPagedList<Post> cat2 { get; set; }
}

in controller class

_repository.cat1 = this._postService.GetPostByParams(...);
_repository.cat2 = this._postService.GetPostByParams(...);
return View(_repository)

I cannot get the right data from this model.

I am new to ASP.NET MVC4 and I am confuse about passing complex model to view.

Upvotes: 0

Views: 1111

Answers (1)

RKS
RKS

Reputation: 1410

Please create a ViewModel which maps to each of your Views. In these ViewModels, you can specify multiple Models and use them accordingly in Views.

Upvotes: 1

Related Questions