Sometimes I have to fill a model before I pass it to a view. I can do it in an action in a controller:
public class FormController
{
public ActionResult Index(int recruitmentId, int employerId)
{
EmploymentForm employmentForm = new EmploymentForm();
employmentForm.StartDate = new DateTime();
employmentForm.RecruitmentId = recruitmentId;
employmentForm.EmployerId = employerId;
// much more properties with some logic (for example connect to database to fill them)
return View(employmentForm);
}
}
But then the action is very long so I create my own class and I fill the model there:
public class EmploymentFormInitializator
{
private int _recruitmentId;
private int _employerId;
public EmploymentFormInitializator(int recruitmentId, int employerId)
{
_recruitmentId = recruitmentId;
_employerId = employerId;
}
public EmploymentForm Init()
{
EmploymentForm employmentForm = new EmploymentForm();
employmentForm.StartDate = new DateTime();
employmentForm.RecruitmentId = _recruitmentId;
employmentForm.EmployerId = _employerId;
// much more properties with some logic (for example connect to database to fill them)
return employmentForm;
}
}
Then my controller is very short:
public class FormController
{
public ActionResult Index(int recruitmentId, int employerId)
{
EmploymentFormInitializator employmentFormInitializator = new EmploymentFormInitializator(recruitmentId, employerId);
EmploymentForm employmentForm = employmentFormInitializator.Init();
return View(employmentForm);
}
}
What pattern I use in that case? Is EmploymentFormInitializator class maybe a factory, builder or maybe it isn't any pattern?
Aucun commentaire:
Enregistrer un commentaire