我正在寻求有关如何使我的 MVC 代码更高效的帮助,因为我在我的 Create GET 和 POST 操作中重用了相同的代码,这违反了 MVC 的 DRY 原则。
具体来说,我正在使用 EntityFramework 并有一个控制器,该控制器使用以下代码填充 ViewModel:
public ActionResult Create()
{
var fileManagers = from x in db.UserProfiles
select x;
var estimators = from x in db.UserProfiles
select x;
var projectManagers = from x in db.UserProfiles
select x;
var jobStatuses = from x in db.JobStatuses
select x;
JobViewModel viewModel = new JobViewModel
{
Job = new Job(),
FileManagers = fileManagers.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList(),
Estimators = estimators.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList(),
ProjectManagers = projectManagers.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList()
};
return View(viewModel);
}
在我的 POST 函数中,我正在检查模型的有效性,然后如果模型无效,则再次写出相同的代码以重新填充我的 ViewModel,这在http://的 ASP.NET 音乐教程中显示www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Job job, string action)
{
if (ModelState.IsValid)
{
db.Jobs.Add(job);
db.SaveChanges();
return RedirectToAction("Index");
}
var fileManagers = from x in db.UserProfiles
select x;
var estimators = from x in db.UserProfiles
select x;
var projectManagers = from x in db.UserProfiles
select x;
var jobStatuses = from x in db.JobStatuses
select x;
JobViewModel viewModel = new JobViewModel
{
Job = job,
FileManagers = fileManagers.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList(),
Estimators = estimators.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList(),
ProjectManagers = projectManagers.Select(x => new SelectListItem
{
Value = x.UserName,
Text = x.FirstName + " " + x.LastName
}).ToList()
};
return View(viewModel);
}
有人可以建议一个更好的方法吗?最好不要添加单独的 ORM 层,因为项目很小。