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,267
  • 2
  • 17
  • 45

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
  • 12,566
  • 16
  • 32
  • 51
0

you should be add Collection of office in City Model

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,226
  • 23
  • 30