Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I define the location of a custom editor template when using MVC areas?

It is my understanding that the location is:

~/Views/Shared/EditorTemplates/ViewModelName

However I have many Views folders using areas. Can I define the file to use with some parameter of the call to the

@Html.EditorFor( ...

Upvotes: 4

Views: 3325

Answers (2)

Nenad
Nenad

Reputation: 26657

Those are default lookup paths which RazorViewEngine will search for editor template, in this order:

"~/Areas/{area}/Views/{controller}/EditorTemplates/{templateName}.cshtml",
"~/Areas/{area}/Views/Shared/EditorTemplates/{templateName}.cshtml",
"~/Views/{controller}/EditorTemplates/{templateName}.cshtml",
"~/Views/Shared/EditorTemplates/{templateName}.cshtml",

If not specified, templateName value defaults to object type (in your case 'ViewModelName'). If template with this name is not found by MVC will fall back to resolve rendering using known build-in templates (int, string, collection, object, etc).

You can specify template name to override defaults:

@Html.EditorFor(m => m.MyDate, "_MyTemplate")

You can also specify relative paths:

@Html.EditorFor(m => m.MyDate, "../_MyTemplate")

You cannot specify full paths in any form (ex:"~/Views/Custom/EditorTemplates/ViewModelName") and you should never specify extension in template name (ex: '_MyTemplate.cshtml', or '_MyTemplate.vbhtml')!

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You could pass the location of the template as second argument.

@Html.EditorFor(x => x.Foo, "~/Views/Custom/EditorTemplates/ViewModelName.cshtml")

This being said I would avoid doing this and stick to the conventions. This means that if you want to use some editor template from outside the area where it is defined then you probably didn't define this template at the right place and should move it in the Shared folder.

Upvotes: -1

Related Questions