Programmatically type an object
C# mvc4 Project
I have two similar ViewModels, that contain over a dozen complex objects, that I want to call a common method from my Create and Edit Actions to populate the ViewModels.
Something along the lines of this
private void loadMdlDtl(CreateViewModel cvM, EditViewModel evM)
{
If (vM1 != null) { var vM = vM1}
If (vM2 != null) { var vM = vM2}
// about two dozen complex objects need to be populated
vM.property1 = …;
vM.property2 = …;
…
}
This doesn’t work because vM
isn’t in scope.
Is there any way to Programmatically type the vM
object so that I don't have to create two loadModel methods or otherwise duplicate a lot of code ?
SOLUTION:
Create an Interface:
public interface IViewModels
{
string property1 { get; set; }
int property2 { get; set; }
IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
}
Have View Models inherit from interface:
public class CreateViewModel : IViewModels, IValidatableObject
{
string property1 { get; set; }
int property2 { get; set; }
IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
{
// implementation
}
}
public class EditViewModel : IViewModels, IValidatableObject
{
string property1 { get; set; }
int property2 { get; set; }
IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
{
// implementation
}
}
Call the method from Actions passing the View Model:
public ActionResult Create()
{
var vM = new CreateViewModel();
...
loadMdlDtl(vM);
...
}
But now accept the interface rather than the View Model into the method:
private void loadMdlDtl(IViewModel vM)
{
// implementation
}