Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 4 > BOOK: Professional ASP.NET MVC 2
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Professional ASP.NET MVC 2
This is the forum to discuss the Wrox book Professional ASP.NET MVC 2 by Jon Galloway, Scott Hanselman, Phil Haack, Scott Guthrie, Rob Conery; ISBN: Professional ASP.NET MVC 2
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional ASP.NET MVC 2 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
 
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old March 1st, 2011, 01:29 PM
Authorized User
 
Join Date: Dec 2010
Posts: 22
Thanks: 10
Thanked 0 Times in 0 Posts
Default Problems with ViewModel Pattern, p88

After making the changes for the ViewModel patter from page 88 to 91, I get this error in the web browser looking at /Dinner/Create:

Server Error in '/' Application.
--------------------------------------------------------------------------------

The model item passed into the dictionary is of type 'NerdDinner.Models.DinnerFormViewModel', but this dictionary requires a model item of type 'NerdDinner.Models.Dinner'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'NerdDinner.Models.DinnerFormViewModel', but this dictionary requires a model item of type 'NerdDinner.Models.Dinner'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[InvalidOperationException: The model item passed into the dictionary is of type 'NerdDinner.Models.DinnerFormViewModel', but this dictionary requires a model item of type 'NerdDinner.Models.Dinner'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Objec t value) +357
System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDi ctionary dictionary) +613
System.Web.Mvc.ViewDataDictionary`1..ctor(ViewData Dictionary viewDataDictionary) +37
System.Web.Mvc.ViewPage`1.SetViewData(ViewDataDict ionary viewData) +93
System.Web.Mvc.ViewPage.set_ViewData(ViewDataDicti onary value) +39
System.Web.Mvc.WebFormView.RenderViewPage(ViewCont ext context, ViewPage page) +120
System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer) +355
System.Web.Mvc.ViewResultBase.ExecuteResult(Contro llerContext context) +409
System.Web.Mvc.ControllerActionInvoker.InvokeActio nResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass14.<InvokeActionRe sultWithFilters>b__11() +60
System.Web.Mvc.ControllerActionInvoker.InvokeActio nResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +391
System.Web.Mvc.<>c__DisplayClass16.<InvokeActionRe sultWithFilters>b__13() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActio nResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +285
System.Web.Mvc.ControllerActionInvoker.InvokeActio n(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestConte xt requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.ICont roller.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessReq uest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidD elegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSy nchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsync Result asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsync Result asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsync Result asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHan dler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.Htt pApplication.IExecutionStep.Execute() +8841105
System.Web.HttpApplication.ExecuteStep(IExecutionS tep step, Boolean& completedSynchronously) +184




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

**********************************************

Any ideas? Or should I post what I changed after it was working?
  #2 (permalink)  
Old March 1st, 2011, 02:00 PM
Authorized User
 
Join Date: Dec 2010
Posts: 22
Thanks: 10
Thanked 0 Times in 0 Posts
Default More Details

Started at page 88, Using ViewModel Pattern. My Nerd Dinner web site was working properly.

* Added the class DinnerFormViewModel in code snippet 1-50.txt. The book didn't say where to put this code but the errata said to put it in the Model folder which seems reasonable to me.

* I made the changes to snippet 1-51, pp 88,9. My only question: what is /Dinners/Edit/5? In the complete code in 1-47 there is a /Dinners/Edit/2. This is what I changed.

* Page 89, The Inherits line I used was this:
Inherits="System.Web.Mvc.ViewPage<NerdDinner.Model.DinnerFormViewModel>"
I changed Controller to Model and added the final quote. Was DinnerFormViewModel class supposed to go in Controllers? (see 1-52)

* Bottom of page 89, 90. Change View code like this:
<p>
<%: Html.LabelFor(m => m.Dinner.Title) %>
<%: Html.TextBoxFor(m => m.Dinner.Title) %>
<%: Html.ValidationMessageFor(m => m.Dinner.Title, "*") %>
</p>
The snippet 1-52 doesn't say to do this, but it's the only way I can think of to get to the Title property.

* page 90, changed code snippet like this according to errata:
//
// POST: /Dinners/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection) {
Dinner dinner = dinnerRepository.GetDinner(id);

if(TryUpdateModel(dinner, "Dinner")) {
dinnerRepository.Save();
* All the rest of the code changes as is on pages 90, 91.

* Run web site and received the error in the first post.
  #3 (permalink)  
Old March 1st, 2011, 04:35 PM
Friend of Wrox
Points: 539, Level: 8
Points: 539, Level: 8 Points: 539, Level: 8 Points: 539, Level: 8
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2010
Location: Seattle
Posts: 106
Thanks: 1
Thanked 17 Times in 17 Posts
Default

Please post the entire code for your Edit method (in DinnersController.cs) or whatever controller method you're having a problem with and I'll see if I can figure it out.
  #4 (permalink)  
Old March 1st, 2011, 05:53 PM
Authorized User
 
Join Date: Dec 2010
Posts: 22
Thanks: 10
Thanked 0 Times in 0 Posts
Default DinnersController

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NerdDinner.Models;

namespace NerdDinner.Controllers
{
    public class DinnersController : Controller
    {
        DinnerRepository dinnerRepository = new DinnerRepository();

        //
        // GET: /Dinners/

        public ActionResult Index()
        {
            var dinners = dinnerRepository.FindUpcomingDinners().ToList();

            return View(dinners);
        }

        //
        // GET: /Dinners/Details/2

        public ActionResult Details(int id)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);

            if (dinner == null)
                return View("NotFound");
            else
                return View(dinner);
        }

        //
        // GET: /Dinners/Edit/2

        [Authorize]
        public ActionResult Edit(int id)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);

            return View( new DinnerFormViewModel(dinner) );
        }

        //
        // POST: /Dinners/Edit/2

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);

            if (TryUpdateModel(dinner, "Dinner"))
            {
                dinnerRepository.Save();
                return RedirectToAction("Details", new { id = dinner.DinnerID });
            }

            return View(new DinnerFormViewModel(dinner));
        }

        //
        // GET: /Dinners/Create

        public ActionResult Create()
        {
            Dinner dinner = new Dinner()
            {
                EventDate = DateTime.Now.AddDays(7)
            };

            return View(new DinnerFormViewModel(dinner));
        }

        //
        // POST: /Dinners/Create

        [HttpPost]
        public ActionResult Create(Dinner dinner)
        {
            if (ModelState.IsValid)
            {
                dinner.HostedBy = "SomeUser";
                dinnerRepository.Add(dinner);
                dinnerRepository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerID });
            }

            return View(new DinnerFormViewModel(dinner));
        }

        //
        // HTTP GET: /Dinners/Delete/1

        public ActionResult Delete(int id)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);

            if (dinner == null)
                return View("NotFound");
            else
                return View(dinner);
        }

        //
        // HTTP POST: /Dinners/Delete/1

        [HttpPost]
        public ActionResult Delete(int id, string confirmButton)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);

            if (dinner == null)
                return View("NotFound");

            dinnerRepository.Delete(dinner);
            dinnerRepository.Save();

            return View("Deleted");
        }

    }
}
  #5 (permalink)  
Old March 1st, 2011, 06:10 PM
Friend of Wrox
Points: 539, Level: 8
Points: 539, Level: 8 Points: 539, Level: 8 Points: 539, Level: 8
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2010
Location: Seattle
Posts: 106
Thanks: 1
Thanked 17 Times in 17 Posts
Default

Can you also post the .aspx ?
  #6 (permalink)  
Old March 1st, 2011, 07:20 PM
Authorized User
 
Join Date: Dec 2010
Posts: 22
Thanks: 10
Thanked 0 Times in 0 Posts
Default /Dinners/Create

Here is /Dinners/Create. i hope that's what you wanted

Code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" %>

<asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
	Host a Dinner
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Host a Dinner</h2>

    <%: Html.ValidationSummary("Please correct the errors and try again.") %>

    <% using (Html.BeginForm()) { %>

        <fieldset>
            <p>
                <%: Html.LabelFor(model => model.Title) %>
                <%: Html.TextBoxFor(model => model.Title) %>
                <%: Html.ValidationMessageFor(model => model.Title, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.EventDate) %>
                <%: Html.TextBoxFor(model => model.EventDate) %>
                <%: Html.ValidationMessageFor(model => model.EventDate, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.Description) %>
                <%: Html.TextBoxFor(model => model.Description) %>
                <%: Html.ValidationMessageFor(model => model.Description, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.Address) %>
                <%: Html.TextBoxFor(model => model.Address) %>
                <%: Html.ValidationMessageFor(model => model.Address, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.Country) %>
                <%: Html.TextBoxFor(model => model.Country) %>
                <%: Html.ValidationMessageFor(model => model.Country, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.ContactPhone) %>
                <%: Html.TextBoxFor(model => model.ContactPhone)%>
                <%: Html.ValidationMessageFor(model => model.ContactPhone, "*")%>
            </p>
            <p>
                <%: Html.LabelFor(model => model.Latitude) %>
                <%: Html.TextBoxFor(model => model.Latitude) %>
                <%: Html.ValidationMessageFor(model => model.Latitude, "*") %>
            </p>
            <p>
                <%: Html.LabelFor(model => model.Longitude) %>
                <%: Html.TextBoxFor(model => model.Longitude) %>
                <%: Html.ValidationMessageFor(model => model.Longitude, "*") %>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

</asp:Content>
  #7 (permalink)  
Old March 1st, 2011, 07:49 PM
Friend of Wrox
Points: 539, Level: 8
Points: 539, Level: 8 Points: 539, Level: 8 Points: 539, Level: 8
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2010
Location: Seattle
Posts: 106
Thanks: 1
Thanked 17 Times in 17 Posts
Default

I think you missed a step on page 89. Somewhere (in the book?) this same thing needs to be done to other views.

Quote:
We’ll then update our View template so that it expects a DinnerFormViewModel instead of a Dinner
object by changing the Inherits attribute at the top of the edit.aspx page like so:
Inherits=”System.Web.Mvc.ViewPage<NerdDinner.Contr ollers.DinnerFormViewModel>

Last edited by flyinhawaiian; March 1st, 2011 at 07:51 PM.. Reason: correction
The Following User Says Thank You to flyinhawaiian For This Useful Post:
ksnortum (March 1st, 2011)
  #8 (permalink)  
Old March 1st, 2011, 08:15 PM
Friend of Wrox
Points: 539, Level: 8
Points: 539, Level: 8 Points: 539, Level: 8 Points: 539, Level: 8
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2010
Location: Seattle
Posts: 106
Thanks: 1
Thanked 17 Times in 17 Posts
Default

Regarding "m.Dinner.Title", note on page 91 the book mentions a "Custom-Shaped ViewModel"

With this in mind, you could do this in your view model.

Code:
public string Title
{
    get { return Dinner.Title; }
    set { Dinner.Title = value; }
}
The Following User Says Thank You to flyinhawaiian For This Useful Post:
ksnortum (March 1st, 2011)
  #9 (permalink)  
Old March 1st, 2011, 08:47 PM
Authorized User
 
Join Date: Dec 2010
Posts: 22
Thanks: 10
Thanked 0 Times in 0 Posts
Default

Quote:
Originally Posted by flyinhawaiian View Post
I think you missed a step on page 89. Somewhere (in the book?) this same thing needs to be done to other views.
I don't disagree with you, but notice that the book doesn't say to do this to other views, and the inheritance line is wrong.
  #10 (permalink)  
Old March 1st, 2011, 08:56 PM
Friend of Wrox
Points: 539, Level: 8
Points: 539, Level: 8 Points: 539, Level: 8 Points: 539, Level: 8
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2010
Location: Seattle
Posts: 106
Thanks: 1
Thanked 17 Times in 17 Posts
Default

Yes, you're right. You'll discover many more things the book left out or didn't get right. When you run into issues, search this forum or post a question. I'll try to answer questions as soon as I can. You'll be happier once you get past chapter 1.
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
State pattern versus Strategy Pattern disel2010 BOOK: Professional ASP.NET Design Patterns 2 March 15th, 2011 08:20 AM
Why is Price a "string" type in the ViewModel instead of Decimal? ksouthworth BOOK: Professional ASP.NET Design Patterns 7 December 18th, 2010 01:06 PM
NerdDinner ViewModel Errata Darthus BOOK: Professional ASP.NET MVC 2 10 September 20th, 2010 01:02 PM
design pattern kishore.dyn Struts 1 February 14th, 2006 02:36 PM
DirectoryInfo.GetFiles(pattern): search pattern fo arif_1947 VS.NET 2002/2003 1 October 19th, 2004 11:59 PM



All times are GMT -4. The time now is 08:15 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.