Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFahmi Eshaq
3,002 PointsWhy do we add two @model directives in a view?
Why do we have two model directives in views: one in _EntryForm and the other one in Edit.cshtml?
Here is a snippet from Add.cshtml:
@model Treehouse.FitnessFrog.Models.Entry -------> model directory#1
@{ ViewBag.Title = "Add Entry"; }
<h2>@ViewBag.Title</h2>
@Html.Partial("_EntryForm") -----------> the partial review has model directory i.e. model directory #2
1 Answer
Steven Parker
231,275 PointsA "partial" view is still a separate view, even though it is rendered on the same page.
It's not like an "include" which would be just a source code extension. So it can have it's own model.
By default, the same model is passed to the partial, but a different model could be passed to the partial by using an additional argument:
Html.Partial("_PartialName", PartialModel);
Fahmi Eshaq
3,002 PointsFahmi Eshaq
3,002 PointsI wonder why this instructor added @model at the top of Add.cshtml when its not necessarily need.
Add.cshtml:
Since you mentioned "By default, the same model is passed to the partial", so I removed @model Treehouse.FitnessFrog.Models.Entry from _EntryForm and kept it in Add.cshtml only and my code failed. I keep getting this error:
HttpCompileException was unhandled by user code An exception of type 'System.Web.HttpCompileException' occurred in System.Web.dll but was not handled in user code Showing error on line 21: @Html.LabelFor(m => m.Date, new { @class = "control-label" }) in _EntryForm
Any idea why I'm getting this error? Given that "By default, the same model is passed to the partial" passed from Add.cshtml to _EntryForm, so why having @model Treehouse.FitnessFrog.Models.Entry in partial?