I am using MVVM here. I have one model Patient.cs
and 3 view models ViewModel1
, ViewModel2
, ViewModel3
. I now have to convert 3 view models into one model.
Can someone please let me know the best way to do it. Below is my code:
ViewModel1.cs
public class ViewModel1 {
[Required]
public string? YearOfBirth { get; set; }
[Required]
public string? DriversLicenseId { get; set; }
}
ViewModel2.cs
public class ViewModel2
{
[Required]
[StringLength(16, ErrorMessage = "First name should be 16 character or less.")]
public string? FirstName { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Last name should be 16 character or less.")]
public string? LastName { get; set; }
[Required]
public DateTime? DateOfBirth { get; set; }
}
ViewModel3.cs
public class ViewModel3
{
[Required]
public string? Address1 { get; set; }
[Required]
public string? City { get; set; }
[Required]
public string? State { get; set; }
[Required]
public string? ZipCode { get; set; }
}
Model Patient.cs
public class Patient
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public Gender? Gender { get; set; }
public string? YearOfBirth { get; set; }
public string? DriversLicenseId { get; set; }
public string? Address1 { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? ZipCode { get; set; }
public string? PaymentType { get; set; }
}
I’m looking for some way to convert all the three view models to Patient.cs
Thanks.
2
Answers
You don’t use to repeat the
variables
Patient.cs
As I see it you would need to do this kind of business explicitly. If it is important for you to maintain the fragmentation of the Model fields across 3 separate view models, then if it was me I would create a type of Super View Model which contained instances of the 3 ViewModel1,2,3 and bind your view Context to an instance of that Super ViewModel instead. You would bind your fields in your view to their respective properties, prefixing the properties with
ViewModel1.
,ViewModel2
orViewModel3
e.g. bind your First Name text field to the propertyViewModel1.FirstName
You can then create an instance of the Patient model class and set the fields explicitly (see theSavePatientRecord
procedure) Something like the following …