【问题标题】:Showing object's name instead of Id in MVC在 MVC 中显示对象的名称而不是 Id
【发布时间】:2018-11-03 20:17:12
【问题描述】:

假设我有一个这样的模型:

public class Branch
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
}

以及示例数据:

Id ----- 姓名 ----- ParentId

01 ----- 父级 ----- 00

02 ----- 孩子----- 01

在 Index.html 视图中,我显示了该表中的项目列表:

如果我想显示父母的姓名而不是 ParentId 怎么办?我可以将父模型与子模型分开,但我希望它们位于同一个表中。

【问题讨论】:

  • 我认为你需要关联两个类表。
  • @Llazar 这只是一类。
  • 那么父母的名字是什么?
  • 添加Branch类型的Parent属性并使用它的Name属性。
  • 你的视图是什么样的?

标签: c# .net asp.net-mvc model controller


【解决方案1】:

您可以考虑使用 ViewModel 来处理这种情况。

public class BranchVM : Branch
{
    // because it extends Branch it has Id, Name, and ParentId
    public string ParentName {get;set;}
}

获取业务逻辑中的字段,然后将此视图模型传递给接受 BranchVM 作为其模型的视图,然后瞧。

【讨论】:

    【解决方案2】:

    在尝试了多种方法后,我决定使用联接,如下所示:

    作为我的模特:

    public class Branch
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? ParentId { get; set; }
    
        [NotMapped]
        public string ParentName { get; set; }
    }
    

    作为我的控制者:

            public ActionResult Index()
        {
            var branches = db.Branches;
            var query = from child in branches
                join parent in branches on child.ParentId equals parent.Id into parentJoin
                select new 
                {
                    Id = child.Id,
                    ParentId = child.ParentId,
                    Name = child.Name,
                    ParentName = parentJoin.FirstOrDefault().Name
                };
            var result = query.ToList().Select(e => new Branch
            {
                Id = e.Id,
                ParentId = e.ParentId,
                Name = e.Name,
                ParentName = e.ParentName
            }).ToList();
            return View(result);
        }
    

    作为我的观点:

    @model List<Rouyesh_Database.Models.Branch>
    @foreach (var item in Model) {
    if (item.ParentId == null)
    {
        <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ParentName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2021-12-27
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多