Question

Instead of using a CheckBoxList helper control I want to use the editor templates of the mvc framework:

In Shared\EditorTemplate I have TemplateViewModel.cshtml

@model ITMS.ViewModels.TemplateViewModel

<p class="checkbox">
@Html.CheckBoxFor(x => x.IsChecked)
@Html.HiddenFor(x => x.Id) 
@Html.LabelFor(x => x.Name)
</p>

As the template must have the same name as the view model... here we go:

public class TemplateViewModel
{  
        public bool IsChecked { get; set; }
        public int Id { get; set; }       
        public string Name { get; set; }   
}

In Home\Delete.cshtml I have:

@model IEnumerable<ITMS.ViewModels.TemplateViewModel>

@foreach (var item in Model)
{
    @Html.EditorFor(m => item)   
}

The output in the Delete.cshtml is a total mess.

I just want that my check-status and name is visible and the id is hidden somewhere.

How do I correct my TemplateViewModel.cshtml/Delete.cshtml ?

Was it helpful?

Solution

In your Delete.cshtml get rid of the foreach loop and simply:

@model IEnumerable<ITMS.ViewModels.TemplateViewModel>
@Html.EditorForModel()

The editor template will automatically be rendered for each element of your model (which in this case is a collection) and you don't need to write any loops.

Also make sure that your editor template is in ~/Views/Shared/EditorTemplates/TemplateViewModel.cshtml. In your question you wrote Shared\EditorTemplate which is a wrong location (you forgot an s at the end). Templates work by conventions that you must follow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top