[ACCEPTED]-ASP.NET MVC3 Partial View naming convention-partial-views

Accepted answer
Score: 63

It's not necessary to use an underscore, but 6 it's a common convention for files which 5 aren't meant to be served directly.

To solve 4 this, you do have the option of returning 3 a View or PartialView with the name of the 2 view as a parameter.

return View("_List");

or

return PartialView("_List");

or inside another 1 view

@{ Html.RenderPartial("_List"); }
Score: 3

If Partial view depends on ActionMethod 5 and always render by Action method, you 4 should same partial view name same as action 3 method like this

public PartialViewResult List()
     {
        DoSomthing();
        //PartialView() return a "List "Parial View  
        return PartialView();
     }

but if your partial view 2 not depends on the action method and directly 1 call by view like this

@Html.RenderPartial("_List"); 
Score: 2

First, there is no shame to be new to any 35 platform. And this was eight years ago so 34 you are probably not new any more. You can 33 use whatever naming conventions you want 32 to use. I go with the original MVC naming 31 convention which uses underscores (_) only 30 for shared views. Partial views should be named after 29 their actions. In your case the name of 28 the view would be Action.cshtml unless this 27 is a shared view of course.

My reasoning 26 is simple. If you call View or PartialView 25 from an action and don't provide a viewName, it 24 assumes the name of the view is the name 23 of the action. Also _Layout.cshtml is named 22 with an underscore. This is because it is 21 shared, not because it is a partial view. This 20 mistake is all over the place in the MVC 19 world. People are really zealously wrong 18 about it. Don't know why. Naming convention 17 is the shop's discretion.

The helper methods 16 Html.RenderAction and Html.Action call actions on the controller. The 15 helper methods Html.RenderPartial and Html.Partial allow you to pass a 14 model directly to a Razor view without passing 13 through an action.

One final thing, call 12 Action instead of RenderAction. RenderAction is only called if you are 11 already inside of a code block. This is 10 almost never the case. I see people using RenderAction and 9 then adding a code block around it unnecessarily 8 just because the build breaks. These two 7 following code snippets are exactly the same and 6 the second one is way more readable in my 5 opinion. I put the div to emphasize that the 4 code is not in a code block:


<div>
    @{ Html.RenderAction("List", "Student"); } 
</div>

<div>
    @Html.Action("List", "Student")
</div>

The bottom line 3 is don't use underscores or curly braces 2 unnecessarily. They are ugly characters 1 and we should avoid them. ;)

More Related questions