Search code examples
c#asp.net-mvc-4razor-2

Listing a ICollection from an object in ASP.NET MVC 4


I have an user class which looks like this

Public class User
    {
        public int UserId { get; set; }

        public string UserName { get; set; }

        [Display(Name = "First Name")]
        public string FullName { get; set; }

        [Display(Name = "Last Name")]
        public string LastName { get; set; }



        public virtual ICollection<Project> Projects { get; set; }
}

And this is my project class

public class Project
    {
        [Key]
        public int ProjectId { get; set; }



        public int ProjectTypeId { get; set; }
        public int UserId { get; set; }

        [Display(Name = "Project title")]
        public string ProjectName { get; set; }
        public string ProjectDescription { get; set; }

        public virtual ProjectDetail ProjectDetail { get; set; }

        public virtual ICollection<ProjectUpload> ProjectUploads { get; set; }

        [ForeignKey("ProjectTypeId")]
        public virtual ProjectType ProjectType { get; set; } 

        [ForeignKey("UserId")]
        public virtual User User { get; set; }

    }

I want to list out the projects for a particular User in the User Index View. How do I do that.


Solution

  • Well, it will be something like:

    -> Index.cshtml

    @using MyApp.Models
    @model MyApp.Models.User
    
    @foreach (Project project in Model.Projects) {
        <div>@project.ProjectName</div>
    }