Brian David Berman: Technical Blog

April 24, 2009

Fun with ASP.NET MVC leads to nice oO Design discovery (Updated)

Filed under: Uncategorized — briandberman @ 3:47 am

I was working through the first chapter of Professional ASP.NET MVC 1.0 and came across a really slick way to handle business rule violations.  Below is some sample code written by Scott Guthrie for the NerdDinner project.

   1: //
   2: // POST: /Dinners/Edit/2
   3: [AcceptVerbs(HttpVerbs.Post)]
   4: public ActionResult Edit(int id, FormCollection formValues)
   5: {
   6:     Dinner dinner = dinnerRepository.GetDinner(id);
   7:  
   8:     try
   9:     {
  10:         UpdateModel(dinner);
  11:  
  12:         dinnerRepository.Save();
  13:  
  14:         return RedirectToAction("Details", new { id = dinner.DinnerId });
  15:  
  16:     }
  17:  
  18:     catch
  19:     {
  20:         ModelState.AddRuleViolations(dinner.GetRuleViolations());
  21:  
  22:         return View(dinner);
  23:     }
  24: }

What’s going on here is that we are editing a Dinner object.  We pass in the ID of the Dinner we are editing as well as the form values from the form post.  At line 6, we instantiate a new dinner object based on the ID passed in.  We then “try” (lines 8-13) to update the model and save it back to the database.  If all goes well and the posted data is valid, the Dinner is saved and we are redirected (line 12).  If, on the other hand, something goes wrong (incorrect or incomplete data is passed in), it safe to say that a business rule has been violated.  Enter our “catch” (lines 14-19).  Since something went wrong, we update our model state with the violations from the GetRuleViolations method on the Dinner object.  We then return the dinner, showing the user the violations to fix.  I think this is, not only a great ASP.NET MVC example, but also a good OO design example.

(Update – Styles for code have been fixed. I am aware that I have some formatting issues.  I just opened this blog and haven’t looked at the CSS yet.  Thanks.)

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.