We have a lot of Controller ActionResult
s like this in our MVC project. The controllers get really cluttered up. This is a simple example, but we have much more complex ActionResult
s.
This controller accepts a model, and if the primary key is Guid.Empty
, handles it as an Add
/Create
. Otherwise it handles it as an edit.
When we started this project we were told that we don't need a Data Layer, since Entity Framework handles a lot of things, but I'm thinking it may be better to have one to handle some of these.
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<ActionResult> _projectedit(ProjectCreate model)
{
if (ModelState.IsValid)
{
Project project = null;
if (model.ProjectId == Guid.Empty)
{
project = new Project()
{
ProjectTypeId = model.ProjectTypeId,
ProjectTemplateId = model.ProjectTemplateId,
Title = model.Title,
Subtitle = model.Subtitle,
CoverImage = model.CoverImage,
Volume = model.Volume,
Issue = model.Issue,
Edition = model.Edition,
CopyrightYear = model.CopyrightYear,
WordCount = model.WordCount,
ProjectDescription = model.ProjectDescription,
CreatedById = SessionUser.ProfileId,
IsActive = true
};
db.Project.Add(project);
}
else
{
project = db.Project.Find(model.ProjectId);
project.ProjectTypeId = model.ProjectTypeId;
project.ProjectTemplateId = model.ProjectTemplateId;
project.Title = model.Title;
project.Subtitle = model.Subtitle;
project.CoverImage = model.CoverImage;
project.Volume = model.Volume;
project.Issue = model.Issue;
project.Edition = model.Edition;
project.CopyrightYear = model.CopyrightYear;
project.WordCount = model.WordCount;
project.ProjectDescription = model.ProjectDescription;
}
db.SaveChanges();
var success = new StringBuilder();
success.Append("<p>");
success.Append(Tools.Format.Title(model.Title, model.Subtitle));
success.Append(" has been created and can be accessed from the <a href=\"/project/\">Projects</a> page");
success.Append(".</p>");
success.Append("<p><a href=\"/\">Return to home page</a>.");
AddMessage(success.ToString());
return RedirectToAction("Edit", "Project", new { id = project.ProjectId });
}
return View(model);
}
AutoMapper
to assign properties so reduce code lines. \$\endgroup\$ – Afshar Mohebi Jul 26 '16 at 6:20