Domanda

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.

È stato utile?

Soluzione

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>
}

Altri suggerimenti

I had a similar issue, but I needed to POST the ICollection back to the controller. It was a pain because the Name attribute for each input needed to be unique and MVC only recognized it as part of the Model if it was named accordingly. So, if anyone else needs it, here is the syntax.

<table>
    @if (@Model != null && @Model.Projects != null)
    {

        for (var i = 0; i < Model.Projects.Count; i++)
        {
            <tr>
                <td>
                    @Html.Hidden("Projects[" + i + "].ProjectId", Model.Projects.ElementAt(i).ProjectId)
                    @Html.Label("Projects[" + i + "].ProjectName", Model.Projects.ElementAt(i).ProjectName)
                </td>
                <td>
                    @Html.TextBox("Projects[" + i + "].ProjectName", Model.Projects.ElementAt(i).ProjectName, new { @class = "form-control" })
                </td>
            </tr>
        }
    }
</table>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top