【问题标题】:ASP.NET MVC how to get name from another model by IdASP.NET MVC 如何通过 Id 从另一个模型中获取名称
【发布时间】:2026-02-13 13:30:02
【问题描述】:

我有一个问题,如何通过外键获取 details.cshtml 中的类别名称 - 工作模型中的 CategoryId?

work.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace InfoKiosk.Domain.Entities
{
    public class Work
    {
        public int WorkId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }
}

category.cs

    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
    }

我从下拉列表中选择的类别名称,我从 ViewBag 中填充。

details.cshtml


<dt>
    <strong>@Html.DisplayNameFor(model => model.Category):</strong> @Html.DisplayFor(model => model.???)
</dt>

【问题讨论】:

    标签: c# html css asp.net asp.net-mvc


    【解决方案1】:

    使用这个

    <dt>
        <strong>@Html.DisplayNameFor(model => model.Category.Name):</strong> @Html.DisplayFor(model => model.Category.Name)
    </dt>
    

    在您的操作中包含类别

    var model=context.Set<Work>().Iclude(c=>c.Category).FirstOrDefault(w=> w.WorkId==id);
    return View(model);
    

    【讨论】:

      【解决方案2】:

      您可以在 ViewBag 中将其传递给视图,可能来自 Controller

      string NameCategory = from c in context.Category
      where c.CategoryId == work.categoryId
      select c.Name
      

      【讨论】: