0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot . But I have solved this problem by just add @model ShowPin.Web.Models.Repository to view ...
You might have solved this issue but in the long run you will run into issues if you don't follow the above method. Creating ViewModels makes life very simple.
Actually, I have add repository model to the view. But I don't know what you mean map to view.
"Mapping to View" means that for each field in your View you can create a separate property in your ViewModel. So, if you have a View with say DropDownList and Textbox, you'll have two properties with return types as List<> and String. Let me know if you need further help on it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.