You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC如何通过Work模型的CategoryId外键在Details视图获取分类名称

解决步骤

  1. 先确保控制器中查询Work数据时加载了关联的Category导航属性
    你需要在对应返回Details视图的Action方法中,使用Include预加载关联的分类数据,示例代码如下:
using System.Data.Entity; // 需提前引入该命名空间

public ActionResult Details(int id)
{
    var work = db.Works
                .Include(w => w.Category) // 预加载关联的Category对象
                .FirstOrDefault(w => w.WorkId == id);
    return View(work);
}
  1. 修改视图中的DisplayFor参数
    直接访问导航属性Category下的Name字段即可,修改后的视图代码如下:
<dt>
    <strong>@Html.DisplayNameFor(model => model.Category):</strong> @Html.DisplayFor(model => model.Category.Name)
</dt>
  1. 可选:添加空值判断避免异常
    如果存在Work未关联分类的情况,可以加判断避免空引用报错:
<dt>
    <strong>@Html.DisplayNameFor(model => model.Category):</strong> 
    @if (Model.Category != null)
    {
        @Html.DisplayFor(model => model.Category.Name)
    }
    else
    {
        <span>未分类</span>
    }
</dt>

内容的提问来源于stack exchange,提问作者user16014328

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:24:02