Why use ASP.NET MVC partial View (.ascx)
As the topic says. What are the reasons and scenarios why I am adding a view for a controller method, that I should sele开发者_StackOverflowct the checkbox "Create a partial view (.ascx)?
The two main reasons would be reusability and readability.
If you plan on having the same information in multiple pages, put it in a View, just like you do with UserControls in WebForms.
If your page is going to be massive, then it might also be a good idea to break out sections into Views. They'll be smaller and easier to read and maintain.
As for creating a view specifically "for a controller method", I personally don't ever create a partial view with the intent to use it directly as the result of a controller method. It usually comes later when you realize you may need to start moving some things around.
As @Brandon points out you use PartialViews for reusability and readability.
Take for example a scenario where you have an IQueryable list of contacts.
You would have a partial view which looped through the list and a partial view which rendered the items.
When you do it that way, you could write code that enabled the looping partial view to decide which partial view should render the contact if there are more than a single way to represent the data.
If you then place those partial views in a shared fodler they can be used throughout the entire application.
Also, you can use an AJAX/jQuery call to a controllers action. That action would then return a PartialView which can then be displayed on screen. Makes your site look very slick when you don't refresh the entire page.
You can use Partial Pages(.ascx files) for :
- Implementing sidebar with common links across multiple pages in a website.
- Avoid template duplication(as explained in NerdDinner example)
The intention for using partial pages is to follow Do Not Repeat Yourself(DRY) principle. Instead of repeating the output view multiple times, a Partial View can be created. This improves re usability and readability
精彩评论