# Wednesday, May 13, 2009

I recently finished reading the first chapter of ASP.NET MVC 1.0, which deals strictly with the Nerd Dinner site that 3 of the 4 authors of the book put together.  This book has been a delight to read to this point and I highly recommend it.  In reading the first chapter I wrote  the code along with the book.  I wanted to make the code a source of reference for me in the future so while I was coding I added comments detailing points of interest from the book.  Along the way I thought making it available to the masses might be a good idea.  Since I wasn't sure on the legal ramifications of putting exact text from a book into my code comments I contacted one of the authors.  I received an email from said author a day later and he stated, and I quote “I say blog first, ask permission later.”  So that is exactly what I am doing.  You can download the full source here. Below is a sample...

        /// <summary>
        /// Attempts to perform an edit on the Dinner with the provided id using the provided formValues
        /// URL     :   /Dinners/Edit/[id]
        /// Verb    :   Post
        /// Purpose :   Save the form changes for a particular Dinner to the database
        /// </summary>
        /// <param name="id">Id of dinner to edit</param>
        /// <param name="formValues">Incoming form parameters</param>
        /// <returns>Details for view for the dinner that was edited</returns>
        /// <remarks>
        /// The "AcceptVerbs" attribute indicates it handles HTTP Post scenarios.
        /// When the attribute is applied to overloaded action methods ASP.NET MVC
        /// automatically handles dispatching to the appropriate action method depending
        /// on the incoming HTTP verb.
        /// For details on why MVC differentiates via HTTP verbs and doesn't use the 
        /// multiple URL approach see page 64.
        /// </remarks>
        public ActionResult Edit(int id, FormCollection formValues) {
            //Call method on our DinnerRepository to get the Dinner being edited
            var dinner = _dinnerRepository.GetDinner(id);
            //Verify that a dinner was found
            if (dinner == null)
                return View("NotFound");
            //Verify that the logged-in user matches the dinner host
            if (!dinner.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");
            //The "try" block will catch errors in calling UpdateModel or when we
            //try and save the DinnerRepository, which will throw if the Dinner object
            //we are tyring to save is invalid because of a rule violation.
            try {
                //The "UpdateModel" helper method on the Controller base class supports updating
                //the properties of the object being passed to it using the incoming form parameters.
                //It uses reflection to determine the property names on the object, and then automatically
                //converts and assigns values to them based on the input values submitted by the client.
                //The method will automatically update the "ModelState" collection when it encounters errors
                //while trying to assign form values to properties on the model object.  For example putting 
                //something other than a DateTime in the EventDate field.
                //Persist the changes
                //Return the Details view for the dinner being edited
                return RedirectToAction("Details", new{id = dinner.DinnerId});
            catch {
                //Handle edit errors
                //****** The code below was refactored to an extension method in the class ControllerHelpers
                ////Loop through the rule violations and add to ModelState
                //foreach (var issue in dinner.GetRuleViolations()){
                //    //The "ModelState" property collection provides a way to indicate that
                //    //errors exist with a model object being passed to a view.  Error entries
                //    //within the the "ModelState" collection identify the name of the model 
                //    //property with the issue and allow a human-friendly error message to be specified.
                //    //HTML helper methods like "HTML.TextBox" check the "ModelState" collection to see 
                //    //if there were any errors associated with the property on the model object the control
                //    //is associated with.  If it determines that there was an error it renders the submitted user
                //    //input as the value and adds a CSS error class to the markup it generates.
                //    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                //Example below uses ViewData...which is not strongly-typed
                //Add the SelectList to ViewData so the Countries drop down list is populated when rendered
                //ViewData["countries"] = new SelectList(PhoneValidator.Countries, dinner.Country);
                //Example using ViewModel which is strongly-typed
                return View(new DinnerFormViewModel(dinner));
                //Return the Dinner view
                //return View(dinner);

Thursday, May 14, 2009 1:41:12 PM (Central Daylight Time, UTC-05:00)
Thanks for making this available.
Thursday, January 13, 2011 12:40:48 AM (Central Standard Time, UTC-06:00)
Giving someone all your love cheap ugg boots sale is never an assurance that they will love discount ugg boots you back! Do not wait for love in return,just wait for cheap ugg boots it to grow in their ugg boots heart but if does not,be content it grows in ugg boots sale yours.It takes only a minute to get a crush on someone,but it takes a http://www.goodfurboots.com/ lifetime to forget someone.
Thursday, January 20, 2011 11:52:00 PM (Central Standard Time, UTC-06:00)
For every single act new era caps that is senselessly
destructive,DC Hats there are thousands more small,
quiet Fox Hats acts of love, kindness and compassion.
Forevery NFL Hats person who seeks to hurt, there are many,
many more who devote heir lives to helping and MLB Hats to healing.
Friday, January 21, 2011 12:00:22 AM (Central Standard Time, UTC-06:00)
"Relish the moment " is a good Red Bull Hats motto,
especially when coupled with New York Yankees Hats Psalm
118:24:"Thisis the day which the Lord Monster Energy Hats hath
made;we will rejoice and be glad in it. " It isn't the burdens of today that drive men mad. It is the regrets over yesterday and the
fear of tomorrow. Regret new era hats and fear are twin thieves who rob us of today.

Monday, March 25, 2013 5:58:30 AM (Central Standard Time, UTC-06:00)
I can see that you are very good at this, so why don't you get an admin job? It is a job well paid and I can bet that you will love it. Don't waste your time and apply for a job right now! I know a few friends who didn't regret to have this job!
Wednesday, November 19, 2014 6:21:52 AM (Central Standard Time, UTC-06:00)
whoah this blog is fantastic i love studying your posts. Staay up the great
work! You realize, lots of persons are hunting around for this information, you can aid them greatly.

Heree is my blog print advertisement - http://friendfeed.com/festivecontract/b9b94362/get-friend-sweeper-review-friendsweeper -
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview