I have 2 lists in from the MainVM
view model, I would like if by iterating through these 2 lists the values can be extracted and added to the other list from the DescRecordsVM
view model.
To give an example of what I want to do is iterate the Attachments
list and save the values to Records
and then iterate the Emails
list and save it to Records
as well.
Attachments Records
ID = 5 --> ID=5
documentName = "file.pdf" --> Description = "file.pdf"
dpcumentType="PDF" --> Type="PDF"
Emails Records
ID = 7 --> ID=7
EmailName = "Progress" --> Description = "Progress"
dpcumentType="GMAIL" --> Type="GMAIL"
I wanted to know if this is possible to do if you can give me how the code can be to do this in a method to return the Records View model or is there another way to do it?
Main view models:
public class MainVM
{
public List<AttachmentVM> Attachments { get; set; }
public List<EmailVM> Emails{ get; set; }
}
public class AttachmentVM
{
public Guid Id { get; set; }
public string documentName { get; set; }
public string documentType { get; set; }
}
public class EmailVM
{
public Guid Id { get; set; }
public string EmailName{ get; set; }
public string EmailType { get; set; }
}
New view model
public class DescRecordsVM
{
public List<DescriptionVM> Records { get; set; }
}
public class DescriptionVM
{
public Guid Id { get; set; }
public string Description{ get; set; }
public string Type{ get; set; }
}
The controller receives the ID fills the lists from the database.
public async Task<ActionResult> GetCommunications(long id )
{
var vm = new ViewModels.MainVM();
vm.Attachments = GetAttachments(id).ToList();
vm.Emails= GetAttachments(id).ToList();
// This is where my idea is to iterate through each list
// and fill the `Records` list from `DescRecordsVM`
// view model with the values.
return PartialView("view",Records);
}
2
Answers
You can convert your AttachmentVM and EmailVM using Select method.
I hope I understood correctly.You want to add all the elements(AttachmentVM,EmailVM) inside this to the record class(DescriptionVM).I did this with AutoMapper
Nuget package:
1.AutoMapper 2.AutoMapper.Extensions.Microsoft.DependencyInjection
Controller:
Action
Program:
Mapping
example data: