【问题标题】:How to display table column using the ID of another table?如何使用另一个表的 ID 显示表列?
【发布时间】:2019-12-16 07:37:14
【问题描述】:

这是我的课程:

我想在@Html.DisplayFor 中显示应该与 Office 类的 CityID 匹配的 CityName。 我该怎么做?

【问题讨论】:

    标签: c# visual-studio model-view-controller razor


    【解决方案1】:

    你应该在城市模型中添加办公室集合

    【讨论】:

      【解决方案2】:

      首先,您应该创建类似于 OfficeViewModel 的 ViewModel 名称

      其次,在服务器端,你可以通过 Office.CityId 和 City 之间的连接获得价值CityName

      希望This 的帖子对您​​有所帮助。

      【讨论】:

        【解决方案3】:

        您可以使用以下代码。我有班级OfficeViewModel

        public class OfficeViewModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int CityId { get; set; }
            public string CityName { get; set; }
        
        }
        

        那么如果我们调用Office列表OfficesCity列表Cities你可以用下面的代码做到这一点

        public IActionResult GetOffices(){
        
               List<OfficeViewModel> viewModel = Offices.Select(x => new OfficeViewModel
               {
                    Id = x.Id,
                    Name = x.Name,
                    CityId = x.CityId,
                    CityName = Cities.FirstOrDefault(y => y.CityId == x.CityId).CityName
                }).ToList();
        
                return View(viewModel);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-15
          • 2010-09-28
          • 1970-01-01
          • 2015-07-03
          • 2018-08-30
          相关资源
          最近更新 更多