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
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).
On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.
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.
By default Razor Pages are stored in Pages folder under project root.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With