What are the differences between editor templates and partial views? - asp.net-mvc

I am simply looking for how these two are different and what are their pros and cons?
It seems you can do all with partial views that you can do with templates.

If you are referring to EditorTemplates (rather than inline timeplates), then there are some big differences. First, partial views require you to specify your view when you use them, while templates work on the type of the data object.
Second, because templates work on data types, then when you make a change to the template, it changes it everywhere that type is used, not just where the partial view is used (this can be a disadvantage as well in some cases).
Third, templates are passed additional information that partial views are not, in particular you recieve Model Metadata, such as that created by attributes.

if you mean "inline helpers", they are simply an easier way of building the equivalent of HtmlHelper extension methods - but they are only for use in the specific view. partial views, on the other hand, can have more logic behind them (via their controller) without violating MVC and they can be easily reused from multiple views

Related

What is the difference between Dynamic and Strongly Typed Views in ASP.Net MVC

I got a url http://www.asp.net/mvc/overview/views/dynamic-v-strongly-typed-views
they create a not strongly typed view but at they refer #model dynamic at top of the view.
but rest of the code looks like normal strongly typed view. anyone can tell me what is the difference between Dynamic and Strongly Typed Views in MVC.
When one should use dynamic view. discuss with example when dynamic view is required ?
The difference is that a dynamic view won't enforce compile-time type-checking (binding to properties etc). You can name and bind any property you want. At run time, if it can't find it in the model, that's when you'll get an error. It's the same as the dynamic keyword in the language.
As to why or when to use it, generally speaking, don't. It's a workaround. Write a wrapper class, write the DTO, write an adapter, there's plenty of ways to make a strongly typed object to bind to. Implement an interface or something.
Rarely you might come across a situation where it's just not feasible (legacy code, 3rd party libraries?) to do it the "right" way. That's when you might be stuck with it. Run time errors are not fun to try to recover from - try to never use dynamic views.
The only time I personally have used it was to mock up test layouts and I didn't want to actually create full models yet. I'd not use it for production code.

Zend2: View helper vs Partial view

This is actually a follow up question to this. When is it better to use a partial view and when is it better to use a view helper?
View helpers
Are normally used if you need to add some repetitive/complex logic within the view. A good example of this are some of the already provided view helpers, such as the Zend\View\Helper\Url.
The Zend\View\Helper\Url is designed to abstract away the repetitive construction of URLs, which otherwise would be considerably messy (and error prone) to do each time you need a link.
echo $this->url('zfcadmin/admin', array('action' => 'index');
/** /admin/home **/
The great thing regarding all view helpers is the ability to provided varied data, to a simple API, and have the output be constructed and returned to the view without the view being aware of how the data was generated.
In the case of the URL view helper; There is complex interaction with the Router and it make sense for all of this to be completed in one place.
View Partials
Conversely, view partials are all about "injecting" HTML (or other view data) fragments into other templates. They reduce the need to repetitively write the same HTML structure where only some of the variables are different; Allowing you to create views scripts as reusable 'templates'.
The documentation states
The Partial view helper is used to render a specified template within its own variable scope. The primary use is for reusable template fragments with which you do not need to worry about variable name clashes
I would often use a view partial where there is a small block of HTML that should be reused either as as "widget" or something within a loop.
Note
As there is a clear distinction between what the view partials and view helpers are trying to accomplish, you will often use them in tandem to create your final output. For instance a view partial that you include with $this->partial('/module/foo/bar.phtml', array()); may actually use a view helper within the '/module/foo/bar.phtml (as it is also a view).
Note 2
Just to confuse you even more, when you use $this->partial(); in your view; You are actually using the built in partial view helper Zend/View/Helper/Partial

ASP.NET MVC: When to use HTML helpers in views - Tidying up the code!

I am trying to refactor my views a bit and up til now i have been using the built HTML helpers but i thought i would create my own - they're extension methods right?
I wonder if anyone can confirm or give advise when an HTML is needed? I think i once saw a document that said if you use 1 IF statement in your views encapsulate it into a html helper - would anyone agree with that?
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
Or possible i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
Thanks in advance
Use HTML helpers when you want to encapsulate the output of a piece of HTML markup that can take varying values.
I'd recommend creating them as extension methods to HtmlHelper rather than creating your own class, as your own class won't be available inside of the default ViewPage without either instantiating a new instance inside of the View or subclassing ViewPage and using this in the View (or passing in on the model, but that's just wrong!).
HTML Helpers are extension methods. I can confirm as well that I too use the 'if' rule when it comes to views. Any view logic coded should, IMO, be in a helper.
You can use helper to render custom markup, or control which markup(ie existing view) is displayed.
Not too sure about the ease of this, but it does lend itself to more unit testing (please comment on this aspect if someone has more info).
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
If I understand correctly, in this respect my suggestion would to separate your helpers into their own classes. The reasoning behind this for me would be that you easily know when looking at your views what are standard helpers vs the ones you've created. I think this will improve maintainability.
i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
I'd say No! (or it depends). One of the benefits of using a helper would be to reuse the same view logic in multiple views as opposed to re-coding the same if statements. This means your code is more DRY, which is always better. In the event you need to debug some weirdness error, you only need to look in one place, the newly created helper.

When should I use HtmlHelper Extension Methods?

I am increasingly finding situations where my ASP.NET MVC view requires some logic to perform layout. These routines have no place being in either my model or my controller. I have 3 options:
Write lots of <% %> inline in the view.
Write less <% %> in a number of partial views.
Write an HtmlHelper Extension method.
It is the last option that confuses me. Is it OK to do this if the logic is specific to only that one view? The extension would be 'visible' to the Html object of every other view, and it will never be needed.
Any suggestions?
I personally prefer option 3 ("Write an HtmlHelper Extension method") because those bodies of code lend themselves to be easily unit testable.
I really do wish extension methods could be placed on internal or nested classes because you are right, you will begin to pollute your namespaces with tons of extension methods which are only used in one View.
I'd recommend sequestering these HtmlHelper extension methods in static classes in a custom namespace per View that you manually reference in the View so as to limit the number of extension methods available throughout your project.
I would, generally, limit both partial views and extension methods to reusable components, but am not pedantic about it. If you feel that either one improves the readability of your code, then go ahead and use them. You might want to consider a separate namespace/helper class for helper methods that are only used by one set of views -- sort of like segregating your partials per controller.
You might also want to consider using more whitespace (even though it's the silent killer) to improve readability. I've implemented output compression in my base controller to limit the impact of whitespace on download time.
Is it OK to do this if the logic
is specific to only that one view?
Yes. Read on...
The
extension would be 'visible' to the
Html object of every other view, and
it will never be needed.
No true. It depende how you register the extension method for the view. This is only the case if you add the namespace to the web.config namespaces section.
If you want to use the extension method on a single view just import its namespace to the single view:
<%# Import Namespace="NamespaceOf.Your.ExtensionMethods.ForThisViewOnly"%>

What should the view file/directory structure be in ASP.NET MVC?

I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.
Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.
Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter?
View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions about them. If you do not conform to these assumptions, then you must write code to let the framework know what you are doing. Generally speaking, you should conform to these assumptions unless you have a good reason not to.
Let's look at the simplest possible controller action:
public ActionResult NotAuthorized()
{
return View();
}
Because no view name has been specified in the call to View(), the framework will presume that the view filename will be the same as the Action name. The framework has a type called ViewEngine which will supply the extension. The default ViewEngine is WebFormViewEngine, which will take that name and append an .aspx to it. So the full filename in this case would be NotAuthorized.aspx.
But in which folder will the file be found? Again, the ViewEngine supplies that information. With WebFormViewEngine, it will look in two folders: ~/Views/Shared and ~/Views/{controller}
So if your controller was called AccountController, it would look in ~/Views/Account
But there might be times when you don't want to follow these rules. For instance, two different actions might return the same view (with a different model, or something). In this case, if you specify the view name explicitly in your action:
public ActionResult NotAuthorized()
{
return View("Foo");
}
Note that with WebFormViewEngine, the "view name" is generally the same as the filename, less the extension, but the framework does not require that of other view engines.
Similarly, you might also have a reason to want your application to look for views and non-default folders. You can do that by creating your own ViewEngine. I show the technique in this blog post, but the type names are different, since it was written for an earlier version of the framework. The basic idea is still the same, however.
In regard to expected names for the views, I think that it's one of those things that each project or organization will try to standardize.
As you hinted to in your question, it's possible that some of these Views (or more precisely, the Actions that render them) become popular across the board, like for example the ones below that are common in RoR applications that adopt the REST paradigm:
/orders/ (i.e. index)
/orders/show/123
/orders/edit/123
/orders/update/123
/orders/new
/orders/create
/orders/destroy/123
The choice/standardization of the Views is largely dependent on how you model your application (to say the obvious) and how fine-grained you want to go. The closer you map your controllers to individual model classes (cough...resources...cough), the shorter your actions will tend to be and more easily you will be able to follow a standard set of actions (as in the above example).
I also believe that shorter actions help pushing more and more of the model business logic into the models themselves, where it belongs.

Resources