Render partial from different folder (not shared)

前端 未结 10 2010
名媛妹妹
名媛妹妹 2020-11-29 17:12

How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to

10条回答
  •  臣服心动
    2020-11-29 17:39

    If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.

    Add a class to your Models folder:

    public class NewViewEngine : RazorViewEngine {
    
       private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
          "~/Views/Foo/{0}.cshtml",
          "~/Views/Shared/Bar/{0}.cshtml"
       };
    
       public NewViewEngine() {
          // Keep existing locations in sync
          base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
       }
    }
    

    Then in your Global.asax.cs file, add the following line:

    ViewEngines.Engines.Add(new NewViewEngine());
    

提交回复
热议问题