MVC Partial Views in a Custom Directory

by StoneJunction 10. January 2012 03:56

 

If you stop the debugger in a MVC controller and have a dig down in ViewEngines.Engines you will find a property PartialViewLocationFormats



When using @Html.Partial(“{_YourView}”)  razors view engine looks in the 4 default locations. The {0} represents the view name and {1} is the controller name.

If you move your partials to a different directory you will get an error screen as it can’t find the file on the default paths its loading. To work around this you can set your own custom ViewEngine with the the paths to your specific location. So for example if you were storing the partials in /Partials then you would use:

public class MyViewEngine : RazorViewEngine 

    {

        private static readonly string[] NewPartialViewFormats = new[]

                                                                     {

                                                                          "~/Views/Shared/Partials/{0}.cshtml",

                                                                     };

        public MyViewEngine()

        {

            base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();

        }

    }

And then in the global.asax.cs you would call it at startup:

protected void Application_Start(Object sender, EventArgs e)
        {            
            ViewEngines.Engines.Add(new MyViewEngine());
        }

Tags: , ,

General | MVC | C# | Razor

CS1502 Error when Rendering a MVC Partial View

by StoneJunction 6. January 2012 23:58

I am just getting up to speed on MVC3 with Razor and when creating a partial view ("_TestPartial.cshtml") and including it on another page through with:

    @Html.RenderPartial("_TestPartial") 

I got the error:

    CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments

Looking at RenderPartial it returns a void. Internally it writes directly to the response. A quick razor syntax change to:

    @{ Html.RenderPartial("_TestPartial"); } 

sorted the problem. Now for the interesting problem of getting MVC partials to render on classic aspx webpages.

Tags: ,

Computing | Programming | C# | MVC | Razor