Skip to content

Instantly share code, notes, and snippets.

@angularsen
Last active August 29, 2015 14:14
Show Gist options
  • Save angularsen/b2d365a0078c9eadec19 to your computer and use it in GitHub Desktop.
Save angularsen/b2d365a0078c9eadec19 to your computer and use it in GitHub Desktop.
Update pattern for MVC + Dal
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditFooVm vm)
{
if (!ModelState.IsValid)
{
SaveModelState();
return RedirectToAction("Edit", new {id = vm.FooId});
}
if (!await _auth.CheckAccessAsync(User, vm.FooId, AccessFlags.Update))
{
return HttpNotFound(MessageFooNotFoundOrNotAuthorized);
}
await _versions.UpdateAsync(vm.FooId, w =>
{
w.Label = vm.Label;
// ..and other properties exposed by FooDal.UpdateWhitelist
});
return RedirectToAction("Index");
}
public async Task UpdateAsync(Guid id, [NotNull] Action<UpdateWhitelist> update)
{
if (update == null) throw new ArgumentNullException("update");
Foo existing = await _db.Foos.FindAsync(id);
if (existing == null)
throw new NotFoundException("Foo not found. Id: " + id);
update(new UpdateWhitelist(existing));
existing.LastModified = DateTimeOffset.UtcNow;
await _db.SaveChangesAsync();
}
// Nested type of FooDal, in a separate file using partial class
public class UpdateWhitelist
{
private readonly Foo _existing;
public UpdateWhitelist([NotNull] Foo existing)
{
if (existing == null) throw new ArgumentNullException("existing");
_existing = existing;
}
public string Label
{
get { return _existing.Label; }
set { _existing.Label = value; }
}
// .. other white listed properties
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment