Asp.net-mvc3 Editor For Template Name

I had a strange problem with the editorFor assistant from MVC3. Here's what: I'm trying to display a checkboxList, and it works if I don't call explicity the template name. However, if I try to use the template name, it throws an exception saying that I am trying to pass a generic list when I just need to pass my viewModel. I will show the code to make it more clear:

ViewModel

public class ChkViewModel { public string ContractName {get;set;} public string Contract {get;set;} public bool Checked {get;set;} } 

Editor for the template (it is called ContractTemplate)

 @model Models.ChkViewModel <p> @Html.HiddenFor(x => x.Contract ) @Html.LabelFor(x => x.ContractName , Model.ContractName ) @Html.CheckBoxFor(x => x.Checked, new { @class = "chkContract" }) &nbsp; </p> 

Excerpt from my view

 <div id="contractContainer"> @Html.EditorFor(item=>item.ContractList) </div> 

It works great. But he is trying to do this:

 <div id="contractContainer"> @Html.EditorFor(item=>item.ContractList, "ContractTemplate") </div> 

It throws an InvalidOperationException that I need to pass a simple ChkViewModel, not a ChicViewModel GenericList.

I am only asking about this because I was trying to create another checkboxlist, and I could not get it to work (not even showing the flags), and when I was trying to set the template name so that I could at least see the flags, this error.

+7
source share
1 answer

The error message is correct, if you want to use the name of your template, it should look like this:

 <div id="contractContainer"> @for (int i = 0; i < item.ContractList.Count; i++) { @Html.EditorFor(item => item.ContractList[i], "ContractTemplate") } </div> 

This is similar to what ASP.NET MVC does behind the scenes for you in the first case (it iterates through the collection and invokes your template).

+6
source

All Articles