EditorForModel does not render ICollection property

I am using the EditorForModel helper on a class that have a property of type ICollection<int> unfortunatlly I can not see my control render in my page.

Here is the sample:

The model view object

public class CopyFromVM
{

    [UIHint("MultiEntityList")]
    public ICollection<int> EntityIds { get; set; }
    ...
}

In the EditorTemplate folder I have the file MultiEntityList.cshtml

@model ICollection<int>


<select name="@ViewData.ModelMetadata.PropertyName" id="@ViewData.ModelMetadata.PropertyName" multiple="multiple" >
 ...
</select>

When the form is render I don't have any error of any kind. The properties is just ignore from the rendering. So I am suspecting that EditorForModel is ignoring complex type. Looking at the web it should work properly for all type.

thanks for the help.

Answers


The following should pick up the custom template from your main view:

@model CopyFromVM
@Html.EditorFor(x => x.EntityIds)

The following will not:

@model CopyFromVM
@Html.EditorForModel()

The reason for that is because the framework doesn't recurse into complex object properties. You could modify the Object.cshtml default editor template as explained by Brad Wilson in this blog post (look at the Shallow Dive vs. Deep Dive section towards the end of his post).

Also make sure that your editor template is placed into the correct folder: ~/Views/Shared/EditorTemplates/MultiEntityList.cshtml and not EditorTemplate as stated in your question (notice the missing s).


As a side remark, the way you are generating the name and id attributes of your select list inside the editor template is not correct because you are not taking into account the nesting level. Imagine for example that CopyFromVM is used as a property of yet another parent view model. In this case the name of the select will be wrong and the default model binder won't be able to rehydrate the value: Use the following instead:

@model ICollection<int>
<select name="@ViewData.TemplateInfo.GetFullHtmlFieldName("")" id="@ViewData.TemplateInfo.GetFullHtmlFieldId("")" multiple="multiple" >
    ...
</select>

Well, actually, no, you already have helpers that do this job for you @Html.ListBox. Hardcoding HTML form elements in ASP.NET MVC views seems a pretty fragile process that I would recommend you to avoid.


And yet another side remark: in order to generate a select list you normally need 2 properties on your view model: one that will hold the selected values and one that will hold all the values. So strongly typing your editor template to ICollection<int> is IMHO a wrong approach here.


Need Your Help

How does SSL protect the data against sniffing?

java security ssl encryption

I've got a small website and it's security is important to me. I don't have the money to buy an SSL certificate so I thought of making one myself (theoretically with java, although I still don't kn...