有时我必须在将模型传递给视图之前填充模型。我可以在控制器中的动作中执行此操作:
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);
}
}
但是动作很长,所以我创建了自己的类,然后在那里填写模型:
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;
}
}
然后我的控制器很短:
public class FormController
{
public ActionResult Index(int recruitmentId, int employerId)
{
EmploymentFormInitializator employmentFormInitializator = new EmploymentFormInitializator(recruitmentId, employerId);
EmploymentForm employmentForm = employmentFormInitializator.Init();
return View(employmentForm);
}
}
在这种情况下我使用什么模式? EmploymentFormInitializator类可能是工厂,构建器还是可能不是任何模式?