I have a question regarding ASP sections and partial views.
What ser the benefit of using one over another?
Because if I have a menu, i guest that it could be both as a section, but also as a partial view.
So what is the difference?
2 Answers 2
A partial view is used when you have some view component (optionally with it's own model) that is used in more than one place, or is better separated in to a separate file (for readability, for example).
A section is placed in a master page, and allows individual views to populate those areas - they can mandatory or optional. There aren't really pro's and con's in a comparison between the two, since they serve different purposes.
For your menu example, you may have some mark-up that builds a menu (from a collection) which you would want to to use in many places, then a partial view would be the best option.
If you have a single menu on a page, whose contents change based on the page, then you might use a section to require that the view populates the menu (you may use a partial to populate that menu section too).
-
So a section is basically an empty container? Can a section be populated with a partial view?Robert Harvey– Robert Harvey2013年03月26日 17:23:12 +00:00Commented Mar 26, 2013 at 17:23
-
Yes, the section acts like a empty container in the master page which can(/should) be populated by the view by any means (including a partial). Whilst they are conceptually an empty container, there is most often some semantics and expected content associated with them (such as the menu).Andy Hunt– Andy Hunt2013年03月26日 17:26:01 +00:00Commented Mar 26, 2013 at 17:26
A partial view works well with Model Binding. You can "type-bind" a partial view so that it will "bind" to the model provided.
@Html.Partial("_NavigationMenu", Model.Navigation)
A Section is basically like a "placeholder" or "literal" which will just output whatever code is placed within the region in it's appropriate location defined in the "parent".
@section JavaScript{
//some code to be included on the "parent" view
}
Generally, I use sections for various ad-hoc script requirements, or CSS, and partial views for DOM elements like formatting (you could use extensions too) / menus / navigation, etc... same idea as the old ".ascx" controls.
Also:
Partial views do not respect section declarations (by design) and therefor cannot be used.