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 trial

C# ASP.NET MVC Forms Finishing Our CRUD Web App Creating a Partial View for Our Form

Fahmi Eshaq
Fahmi Eshaq
3,002 Points

Why 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
Steven Parker
231,269 Points

:point_right: A "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
Fahmi Eshaq
3,002 Points

I wonder why this instructor added @model at the top of Add.cshtml when its not necessarily need.

Add.cshtml:

@model Treehouse.FitnessFrog.Models.Entry -----> Not necessary for Add.cshtml since we are not utilizing Model in Add.cshtml.

@{
    ViewBag.Title = "Add Entry";
}

<h2>@ViewBag.Title</h2>

@Html.Partial("_EntryForm")

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?