0

Here are my classes:

Visual Studio Screenshot

I want to display in @Html.DisplayFor the CityName which is should be a match in CityID of the Office class. How can I do that?

thmspl
  • 2,437
  • 3
  • 22
  • 48

3 Answers3

0

Firstly, You should create ViewModel name looks likes OfficeViewModel

Secondly, In server-side, You can get value CityName by joining between Office.CityId and City.

Hopefully, This post is helpful for you.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

you should be add Collection of office in City Model

zied ben othman
  • 82
  • 2
  • 14
0

You can use the following code. I have class by name OfficeViewModel

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

}

then If we call the Office list Offices and the City list Cities You can do this with the following code

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);
}
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34