/ Published in: C#
A style of code reuse. Breaking methods (in this case MVC controller) into very small reusable atomic chunks that either perform an operation then return an ActionResult OR return null, then using with the null-coalescing operator.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public ActionResult AddComment(CommentAddModel model) { return IfNotValidModelStateViewContent(model) ?? IfNotKnownHumanViewCommentCaptcha(model) ?? AddCommentThenViewReciept(model); } private ActionResult IfNotValidModelStateViewContent(CommentAddModel model) { var contentItem = _repository.FindById<ContentItem>(model.Id); return !ModelState.IsValid ? View(contentItem, model) : null; } private ActionResult IfNotKnownHumanViewCommentCaptcha(CommentAddModel model) { var sessionId = _httpContextProvider.Current.Session.SessionID; var isKnownHuman = _captchaService.IsKnownHuman(sessionId); return !isKnownHuman ? ViewCommentCaptcha(sessionId, model) : null; } private ActionResult AddCommentThenViewReciept(CommentAddModel model) { var contentItem = _repository.FindById<ContentItem>(model.Id); _commentService.AddCommentToEntity(contentItem, model.Body, model.AuthorName, model.AuthorEmailAddress); _repository.Save(contentItem); return ViewCommentReceipt(contentItem.Url); }