Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Good Morning To All Programmers.I'm New to Asp.net MVC4.My question is how can i add two models in single view like
@model IEnumerable<musictrailMVC4.Models.Music>


@model IEnumerable<musictrailMVC4.Models.News>


Im using Scaffold Template.When I'm doing this it shows an error.

Thanks For reading question,Any suggestions are heartly accepted.
Posted
Updated 22-Dec-13 19:20pm
v3
Comments
[no name] 23-Dec-13 1:14am    
So, your business logic needs these two object in another class. if your busienss requirement says that you need a third class then go for another model/viewmodel with these object and bind it.
Ajay_Babu 23-Dec-13 1:18am    
will you give me some examples..

1 solution

You can create another model for your view which contains both of your classes

e.g.
Classes are
C#
public class Music
    {
        public int musicID { get; set; }
        public string musicTitle { get; set; }
    }

    public class News
    {
        public int newsId{get;set}
        public string newsTitle {get; set;}
    }


Then create model for view
C#
public class MusicNewsViewModel
{
    public List<music> MusicList{ get; set; }
    public List<news> NewsList{ get; set; }
}
</news></music>


And in your controller
C#
public ActionResult Index()
{
    var model = new MusicNewsViewModel();
    model.News = // ... fetch Your News
    model.Music = // ... fetch Your Music

    return View(model);
}



And in your view
C#
@model MusicNewsViewModel

@foreach (var music Model.Music)
{
    @Html.DisplayFor(m => music.musicId)
    @Html.DisplayFor(m => music.musicTitle)
}

@foreach (var news Model.News)
{
    @Html.DisplayFor(m => news.UserId)
    @Html.DisplayFor(m => news.UserName)
}
 
Share this answer
 
Comments
Ajay_Babu 23-Dec-13 2:30am    
so i need 3 models,i.e; 1 for music,2 for news,3 for both
Hammad 23-Dec-13 3:26am    
No you just need one model for your view and that is MusicNewsViewModel. Others are classes for you functionality and requirement.
Ajay_Babu 23-Dec-13 5:53am    
How to fetch data in controller from database.I tried a lot but i cant get.
Hammad 24-Dec-13 4:59am    
Have you ever work in MVC if not then first try to learn it..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900