![](/img/trans.png)
[英]How to annotate model classes when you have multiple different (one-to-many, many-to-many) relationships between two classes
[英]How would I have two model classes in one view?
我试图在 ASP.NET MVC 的一个视图中使用两个模型。 我已经在 StackOverflow 上查看了与我的相关的问题,但是我似乎无法让它在我的工作中发挥作用。 我了解如何做到这一点的一般想法,但由于某种原因,我无法让它在我正在处理的代码上运行。
这些是模型类:
public class Project
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime DueDate { get; set; }
public ICollection<ProjectRole> ProjectRoles { get; set; }
}
public class ProjectRole
{
public int Id { get; set; }
[Required]
public double HourlyRate { get; set; }
[ForeignKey("Person")]
public int PersonId { get; set; }
[ForeignKey("Project")]
public int ProjectId { get; set; }
[ForeignKey("AppRole")]
public int RoleId { get; set; }
}
控制器:
[Authorize]
public class ProjectsController : Controller
{
private readonly ApplicationDbContext _context;
public ProjectsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Projects
[Authorize(Roles = "Member")]
public async Task<IActionResult> Index()
{
return View(await _context.Projects.ToListAsync());
}
}
这是观点:
@model IEnumerable< Project2.Models.Entities.ProjectRole>
@{
ViewData["Title"] = "Index";
}
<div class="text-center">
<a href="/"><button>Home</button></a> |
<a href="../People"><button>Manage People</button></a> |
<a href="../People/Report"><button>View People Report</button></a> |
<a href="../Projects"><button>Manage Projects</button></a> |
<a href="../Projects/Report"><button>View Project Report</button></a> |
<a href="../ProjectRoles"><button>Manage Project Role</button></a>
</div>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Person Name
</th>
<th>
Project Name
</th>
<th>
@Html.DisplayNameFor(model => model.HourlyRate)
</th>
<th>
@Html.DisplayNameFor(model => model.RoleId)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PersonId)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProjectId)
</td>
<td>
@Html.DisplayFor(modelItem => item.HourlyRate)
</td>
<td>
@Html.DisplayFor(modelItem => item.RoleId)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
我感谢提供的任何建议和帮助。 谢谢!
你不能在一个视图中使用两个模型,但你可以创建一个视图模型类来包含它们你读过这篇什么是 MVC 中的 ViewModel?
创建一个包含其中两个模型的类,称为视图模型,然后在视图上传递视图模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.