0

I am trying to figure out how to organize my partial views in my project. Some people say to precede the name of a partial view with an _, but that makes for weirdly named actions in the controller if the view can be called directly.

Also, what should be done if the view can be a partial view in some cases and a regular view in other cases?

A common example for this is a search view that I embed on some pages to search for users in my app, but I also have a search page that loads the same view. I suppose I could create a second view for the search page that just embeds the partial view. Just wondering what other people are doing.

pnuts
  • 58,317
  • 11
  • 87
  • 139
Leslie Hanks
  • 2,347
  • 3
  • 31
  • 42

2 Answers2

2

Honestly it's a matter of preference. You should do whatever works in your application with respect to avoiding code (or view) duplication etc.

The reason why we (I'm a dev on the team developing MVC) recommend preceding the partial view filename with an underscore is to more easily distinguish between full and partial views when looking at files in VS

marcind
  • 52,944
  • 13
  • 125
  • 111
  • What do you do about partial views loaded via an action? Do you name the action with an underscore? – Leslie Hanks Aug 13 '11 at 18:46
  • No, since that gets expressed via the URL in the default routing cofiguration. But you should remember that you can always pass in a specific view name into the `View()` or `PartialView()` method. Tour action names and view names do not have to match up perfectly. – marcind Aug 13 '11 at 19:13
  • Aside from passing the names of the views in, you can also just extend the view engine to do this for you: http://stackoverflow.com/a/10692237/32238 (add the "_" convention for the partials, but no need to pass the string in to the View/PartialView methods). – Andrew Theken Jan 31 '13 at 14:13
0

I also use my partials with the underscore character as a prefix to easily distinguish between a view and a partial view when managing the files. As your project becomes bigger you may have a lot of files for a single controller, so this convention will help you a lot. Besides, when you use a partial view you can call your views with an action using the following:

public ActionResult MyPartialAsAView()
{
    // your code
    return View("_myPartialView");
}

You have to remember that if you are using your partial as a View, you should assign the layout to it depending on the mode the partial is working (as a view or partial view), for example with a boolean property on your model class.

Rodrigo Caballero
  • 1,090
  • 1
  • 15
  • 27