HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Saving data in MVC

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mvcsavingdata

Problem

We have a lot of Controller ActionResults like this in our MVC project. The controllers get really cluttered up. This is a simple example, but we have much more complex ActionResults.

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 _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;

Solution


  • Extract that logic into a data layer. Minimally, extract a private Upsert method.



  • Create an extension method for cloning the properties from one of your models to another.



  • Stop this nonsense.



success.Append("");
success.Append(Tools.Format.Title(model.Title, model.Subtitle));
success.Append(" has been created and can be accessed from the Projects page");
success.Append(".");
success.Append("Return to home page.");

AddMessage(success.ToString());


The view logic belongs in the view. Create a partial view that gets conditionally rendered. (Toggled on/off)

Code Snippets

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());

Context

StackExchange Code Review Q#113296, answer score: 6

Revisions (0)

No revisions yet.