Here are my classes:
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?
Here are my classes:
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?
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.
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);
}