I am aware that complex types are not usually rendered when using EditorForModel but I am using a custom object template that does not do the check and calls Html.Editor for every property including complex types.
Unfortunately, whilst I can see the correct TemplateHint value for the property within the object template, the Editor call doesn’t seem to use it and the built in collection template is used instead.
My object template is basically this:
@foreach (var property in ViewData.ModelMetadata.Properties.Where(x => x.ShowForEdit))
{
@Html.Editor(property.PropertyName)
}
If I force the use of the template by passing the name to the Editor call then the ModelMetadata is empty in the template.
Is this a bug / are there any workarounds?
Some more info:
So my view model contains the following:
[ACustomAttribute("Something")]
public IEnumerable<int> SelectedOptions { get; set; }
The attribute implements IMetadataAware and adds some stuff to the AdditionalValues Collection of the ModelMetadata as well as setting the TemplateHint. I can read this data from the object template but not from my custom template.
But please note that if you don’t rely on the established conventions for resolving templates for complex collection types (a.k.a
~/Views/Shared/EditorTemplates/NameOfTheTypeOfCollectionElements.cshtml) and have used anUIHinton your collection property:then the
~/Views/Shared/EditorTemplates/FooBar.cshtmleditor template must be strongly typed toIEnumerable<FooViewModel>and notFooViewModel. So be careful, if this is your case, it’s up to you to loop inside this custom template if you want to get to individual items of the collection. It will no longer be ASP.NET MVC that will automatically loop for you and invoke the editor template for each element.UPDATE:
Still can’t repro your issue.
Custom attribute:
Model:
Controller:
View (
~/Views/Home/Index.cshtml):Editor template for the object type (
~/Views/Shared/EditorTemplates/Object.cshtml):Custom editor template (
~/Views/Shared/EditorTemplates/Something.cshtml):Result:
So as you can see the additional metadata we added is shown in the template.