views:

35

answers:

2

Is there a way to set convention when returning a partial view? For example: I have the following:

HomeController ---> Home(action Method) --> _Home.ascx (partial view)

AboutController ---> About(action Method) --> _About.ascx (partial view)

I'm currently passing the partial view name explicitly to the PartialView helper(ie return PartialView("_home");)

note: without using T4MVC.

Thanks

A: 

I beleive you should always pass partial view name explicitly because code in a file ViewEngineCollection.cs which searches for it raises an exception otherwise:

public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext,
    string partialViewName) 
{
    // skipped code

    if (string.IsNullOrEmpty(partialViewName)) 
    {
        throw new ArgumentException(MvcResources.Common_NullOrEmpty,
            "partialViewName");
    }

    // skipped code
}

Though if you override this method you possibly may use some name convention.

Alexander Prokofyev
A: 

The MVC runtime component that's responsible for mapping a view name to the right file is called a ViewEngine. In case of ascx files it's the default WebFormViewEngine. It exposes properties that contain the default lookup patterns. For example you could modify PartialViewLocationFormats and instead of this:

"~\Views\{1}\{0}.ascx"
"~\Views\Shared\{0}.ascx"

to be this:

"~\Views\{1}\_{0}.ascx"
"~\Views\Shared\_{0}.ascx"

Note that this change will apply to all of your partial view lookups.

marcind
Nice! This led me to overriding webviewformengine's FindPartialView method to string.Format("_{0}",partialView)
bonskijr