Question

I have a partial view display template in Views/DisplayTemplates called Bar.cshtml so that it can be used like:

[DataType("Bar")]  
public FooBar Foo {get;set;}

Unfortunately if I want to use this in an action like return PartialView("Bar",fooModel); it won't find it because it's not in the list of folders searched. At the moment I've made a copy of the file and put it in Views/DisplayTemplates as well as Views, but is there a correct way of doing this with the one file?

Was it helpful?

Solution

Hopefully I've done it now by providing a custom view engine that inherits from the razor view engine and simply adds the view locations to search through:

using System.Linq;
using System.Web.Mvc;

namespace MvcApplication1
{
public class CustomViewEngine : RazorViewEngine
{
    public CustomViewEngine()
        : this(null)
    {

    }

    public CustomViewEngine(IViewPageActivator activator)
        : base(activator)
    {
        var partialViewLocationFormatsList = PartialViewLocationFormats.ToList();

        partialViewLocationFormatsList.Add("~/Views/{1}/DisplayTemplates/{0}.cshtml");
        partialViewLocationFormatsList.Add("~/Views/{1}/EditorTemplates/{0}.cshtml");
        partialViewLocationFormatsList.Add("~/Views/Shared/DisplayTemplates/{0}.cshtml");
        partialViewLocationFormatsList.Add("~/Views/Shared/EditorTemplates/{0}.cshtml");

        PartialViewLocationFormats = partialViewLocationFormatsList.ToArray();

        var areaPartialViewLocationFormatsList = AreaPartialViewLocationFormats.ToList();

        areaPartialViewLocationFormatsList.Add("~/Areas/{2}/Views/{1}/DisplayTemplates/{0}.cshtml");
        areaPartialViewLocationFormatsList.Add("~/Areas/{2}/Views/{1}/EditorTemplates/{0}.cshtml");
        areaPartialViewLocationFormatsList.Add("~/Areas/{2}/Views/Shared/DisplayTemplates/{0}.cshtml");
        areaPartialViewLocationFormatsList.Add("~/Areas/{2}/Views/Shared/EditorTemplates/{0}.cshtml");

        AreaPartialViewLocationFormats = areaPartialViewLocationFormatsList.ToArray();
    }
}
}

And then registered it in Global.asax :

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());     

OTHER TIPS

If you plan to use this in multiple pages you should create a folder in Views/Shared/DisplayTemplates. And to use this template for your FooBar Foo property, decorate it with [UIHint("Bar")] attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top