Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net-mvc3 EditorFor template name issue

i'm having a strange issue regarding the editorFor helper from MVC3. Here's the thing: 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'm trying to pass a Generic list when i should simply pass my viewModel. I'll show some code to make it more understandable:

ViewModel

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

The EditorFor 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>

This works fine. But it try to do this:

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

It throws the InvalidOperationException saying that i have to pass a simple ChkViewModel and not a GenericList ChkViewModel.

I'm only asking this because i've tried to create another checkboxlist and i couldn't make it work (not even display the checkboxes) and when i tried to set the template name, so that i could at least see the checkboxes, it thrown that error.

like image 496
AdrianoRR Avatar asked Nov 22 '11 14:11

AdrianoRR


1 Answers

The error message is correct, if you want to use your template name 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 is ASP.NET MVC doing behind the scenes for you in the first case (it iterates over the collection and call your template).

like image 138
tpeczek Avatar answered Sep 28 '22 05:09

tpeczek