在ASP.NET Core 3.1 MVC中,如果你想在另一个表中显示类别名称而不是视图中的categoryId,你可以通过以下步骤实现:
public class AnotherTable
{
// 其他属性...
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class YourDbContext : DbContext
{
public DbSet<AnotherTable> AnotherTables { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AnotherTable>()
.HasOne(at => at.Category)
.WithMany()
.HasForeignKey(at => at.CategoryId);
}
}
@model
指令声明视图模型,并使用@Html.DisplayFor
辅助方法来显示类别名称。@model IEnumerable<AnotherTable>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Category.Name)</td>
<!-- 其他列... -->
</tr>
}
在上述代码中,假设Category模型具有一个名为Name的属性,用于表示类别的名称。
这样,你就可以在ASP.NET Core 3.1 MVC的另一个表中显示类别名称而不是视图中的categoryId。
领取专属 10元无门槛券
手把手带您无忧上云