Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an automated way to find unused views in MVC?

Does any one know a way to find out unused views in project ? with Resharper or without it. any idea which is easier than writing down all the views and go through all controllers and check manually is appreciated :) Thanks

like image 700
Azadeh Khojandi Avatar asked Nov 21 '11 03:11

Azadeh Khojandi


People also ask

How does a controller find a view in MVC?

MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).

How many views are there in MVC?

On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.

What does return View () in MVC do?

This process determines which view file is used based on the view name. The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called.

Which is a default view search path for the Razor view engine?

By default Razor Pages are stored in Pages folder under project root.


1 Answers

With ReSharper you can right-click a Razor view and Find Usages, but you'd have to go through manually and repeat for all views (unless you can hook into ReSharper's API and automate it).

The problem with views of course is that they're late-bound based on a convention defined in the view engine, in the case of the default RazorViewEngine it looks for a corresponding view in ~/Views/{Controller}/{Action} and ~/Views/Shared/{Action}. So it's difficult to tell at design or compile time which views, partials and templates are never used.

You might approch it from the opposite angle: find which views are being used. Then diff this list against all views in the project, evaluate the results (manually and with ReSharper Find Usages) and confirm they're really not being used before finally removing them.

To find the views being used you could customise the RazorViewEngine to log every time it loads a view with CreateView and FindPartialView, e.g.

public class LoggingRazorViewEngine : RazorViewEngine
{
    protected override IView CreateView(
        ControllerContext controllerContext,
        string viewPath,
        string masterPath)
    {
        LogManager.GetLogger("").Debug(viewPath);
        return base.CreateView(controllerContext, viewPath, masterPath);
    }
}

Configure it in global.asax.cs

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new LoggingRazorViewEngine());

Then extract a list of logged unique view paths to compare against your project's views. Bit of effort involved, but possibly worth if if you've got lots of unused views cluttering up the project.

like image 130
Chris Fulstow Avatar answered Oct 06 '22 21:10

Chris Fulstow