Asp.net 如何在MVC中显示来自外键的数据块的名称
我试图让视图显示类别的名称,而不仅仅是ID 这是我的密码: 型号:Asp.net 如何在MVC中显示来自外键的数据块的名称,asp.net,asp.net-mvc,asp.net-core,Asp.net,Asp.net Mvc,Asp.net Core,我试图让视图显示类别的名称,而不仅仅是ID 这是我的密码: 型号: public class Category { [Key] public string Cat_ID { get; set; } public string Cat_Name { get; set; } } ///////////////////////////////////////////////////////// public class S
public class Category
{
[Key]
public string Cat_ID { get; set; }
public string Cat_Name { get; set; }
}
/////////////////////////////////////////////////////////
public class SubCategory
{
[Key]
public string SCat_ID { get; set; }
public string SCat_Name { get; set; }
[ForeignKey("SCat_Cat")]
public string SCat_Cat { get; set; }
public virtual Category Category { get; set; }
}
子类别控制器(视图零件):
公共子类别控制器(ApplicationDbContext上下文)
{
_上下文=上下文;
}
//获取:子类别
公共异步任务索引()
{
返回视图(wait_context.SubCategory.ToListAsync());
}
应该查看类别名称的代码
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.SCat_Name)
@Html.DisplayFor(modelItem => item.Category.Cat_Name)
</td>
@foreach(模型中的变量项){
@DisplayFor(modelItem=>item.SCat\u名称)
@DisplayFor(modelItem=>item.Category.Cat\u名称)
所以我试图让这部分@Html.DisplayFor(modelItem=>item.Category.Cat_Name)
显示类别名称。现在我什么都没有得到。
哦,这是数据库记录
必须改变这一点:
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.ToListAsync());
}
公共异步任务索引()
{
返回视图(wait_context.SubCategory.ToListAsync());
}
为此:
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.Include(u => u.Category).ToListAsync());
}
公共异步任务索引()
{
返回视图(wait_context.SubCategory.Include(u=>u.Category.toListSync());
}
public async Task<IActionResult> Index()
{
return View(await _context.SubCategory.Include(u => u.Category).ToListAsync());
}