Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ASP.NET MVC partial View (.ascx)

Tags:

asp.net-mvc

As the topic says. What are the reasons and scenarios why I am adding a view for a controller method, that I should select the checkbox "Create a partial view (.ascx)?

like image 851
Shawn Mclean Avatar asked Jan 21 '10 21:01

Shawn Mclean


3 Answers

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.

like image 96
Brandon Avatar answered Nov 04 '22 01:11

Brandon


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.

like image 29
griegs Avatar answered Nov 04 '22 02:11

griegs


You can use Partial Pages(.ascx files) for :

  1. Implementing sidebar with common links across multiple pages in a website.
  2. 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

like image 1
H Sampat Avatar answered Nov 04 '22 02:11

H Sampat