开发者

How does RenderPartial figure out where to find a view?

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)


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.


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.


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).


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜