Search code examples
c#asp.netasp.net-mvcrazorreflection

Iterate ASP.NET MVC views to find all views supporting a specific model type


I would like to get a list of all views that support rendering a specific model type.

Pseudo code:

IEnumerable GetViewsByModelType(Type modelType)
{
   foreach (var view in SomeWayToGetAllViews())
   {
      if (typeof(view.ModelType).IsAssignableFrom(modelType))
      {
         yield return view; // This view supports the specified model type
      }
   }
}

In other words, given that I have a MyClass model, I'd like to find all views that would support rendering it. I.e. all views where the @model type is MyClass, or a type in its inheritance chain.


Solution

  • Based on my findings the compiled views are not included in the assembly, so it's not going to be a walk in the park reflection.

    In my opinion your best bet is going to be to list the .cshtml razor views and then use the BuildManager class to compile the type, which will allow you to get the Model property type.

    Here is an example of looking for all Razor views that have a @Model type of LoginViewModel:

    var dir = Directory.GetFiles(string.Format("{0}/Views", HostingEnvironment.ApplicationPhysicalPath), 
        "*.cshtml", SearchOption.AllDirectories);
    
    foreach (var file in dir)
    {
        var relativePath = file.Replace(HostingEnvironment.ApplicationPhysicalPath, String.Empty);
    
        Type type = BuildManager.GetCompiledType(relativePath);
    
        var modelProperty = type.GetProperties().FirstOrDefault(p => p.Name == "Model");
    
        if (modelProperty != null && modelProperty.PropertyType == typeof(LoginViewModel))
        {
            // You got the correct type
        }
    }