How does RenderPartial figure out where to find a view?

*爱你&永不变心* 提交于 2019-12-23 12:43:12

问题


Ok. Googling fail probably and I remember reading about this a while back but can't find it.

I have a View and a Partial View in different directories. In a view I say @Html.RenderPartial("[partial view name]"); how does RenderPartial figure out where to look? It must be a convention but what is it?

My view is in: WebRoot\Views\Admin\ folder and partial is at WebRoot\Views\Admin\Partials

Not sure if this the right set up.

I'm using MVC 3 (Razor engine)


回答1:


you can, but you have to register the routes, to tell the view engine where to look for. example in Global.asax.cs you'll have:

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

and the class is:

public class RDDBViewEngine : RazorViewEngine
{
    private static string[] NewPartialViewFormats = new[] {         
        "~/Views/Shared/Partials/{0}.cshtml" ,       
        "~/Views/{0}.cshtml"
    };

    public RDDBViewEngine()
    {
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
    }

}

{0} is for all the subfolders with partials.




回答2:


Locating views is the responsibility of the ViewEngine. The WebFormViewEngine was the one originally shipped with MVC 1, and you can see the paths it searches on codeplex. Note that it searches the same paths for views and partial views.

The CshtmlViewEngine (Razor) introduced with MVC 3 (or rather WebMatrix) searches similar locations but looks for different extensions.




回答3:


Each view engine registered in your application has a list of file patterns that will be searched when you reference a view using a simple name (you can also reference it using a full path e.g. ~\Views\Admin\View.aspx)

In MVC 3 the properties of the view engine specify the patterns to search for (this applies to Razor and WebForms view engines).




回答4:


Instead of subclassing the RazorView engine (as was suggested by zdrsh) you can just alter existing RazorViewEngine's PartialViewLocationFormats property. This code goes in Application_Start:

System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
  .Where(e=>e.GetType()==typeof(RazorViewEngine))
  .FirstOrDefault();

string[] additionalPartialViewLocations = new[] { 
  "~/Views/[YourCustomPathHere]"
};

if(rve!=null)
{
  rve.PartialViewLocationFormats = rve.PartialViewLocationFormats
    .Union( additionalPartialViewLocations )
    .ToArray();
}


来源:https://stackoverflow.com/questions/7640790/how-does-renderpartial-figure-out-where-to-find-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!