ASP.NET MVC 3 - Partial vs Display Template vs Editor Template -


so, title should speak itself.

to create re-usable components in asp.net mvc, have 3 options (could others haven't mentioned):

partial view:

@html.partial(model.foo, "somepartial") 

custom editor template:

@html.editorfor(model => model.foo) 

custom display template:

@html.displayfor(model => model.foo) 

in terms of actual view/html, 3 implementations identical:

@model webapplications.models.fooobject  <!-- bunch of html --> 

so, question - when/how decide 1 of 3 use?

what i'm looking list of questions ask before creating one, answers can used decide on template use.

here's 2 things have found better editorfor/displayfor:

  1. they respect model hierarchies when rendering html helpers (e.g if have "bar" object on "foo" model, html elements "bar" rendered "foo.bar.elementname", whilst partial have "elementname").

  2. more robust, e.g if had list<t> of in viewmodel, use @html.displayfor(model => model.collectionoffoo), , mvc smart enough see it's collection , render out single display each item (as opposed partial, require explicit loop).

i've heard displayfor renders "read-only" template, don't understand - couldn't throw form on there?

can tell me other reasons? there list/article somewhere comparing three?

editorfor vs displayfor simple. semantics of methods generate edit/insert , display/read views (respectively). use displayfor when displaying data (i.e. when generate divs , spans contain model values). use editorfor when editing/inserting data (i.e. when generate input tags inside form).

the above methods model-centric. means take model metadata account (for example annotate model class [uihintattribute] or [displayattribute] , influence template gets chosen generate ui model. used data models (i.e. models represent rows in database, etc)

on other hand partial view-centric in concerned choosing correct partial view. view doesn't need model function correctly. can have common set of markup gets reused throughout site. of course times want affect behavior of partial in case might want pass in appropriate view model.

you did not ask @html.action deserves mention here. think of more powerful version of partial in executes controller child action , renders view (which partial view). important because child action can execute additional business logic not belong in partial view. example represent shopping cart component. reason use avoid performing shopping cart-related work in every controller in application.

ultimately choice depends on modelling in application. remember can mix , match. example have partial view calls editorfor helper. depends on application , how factor encourage maximum code reuse while avoiding repetition.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -