asp.net-mvc3 EditorFor template name issue
Asked Answered
P

1

7

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.

Provisional answered 22/11, 2011 at 14:13 Comment(2)
why do you want to specify the template name?Pharmacology
As i mentioned on the last paragraph, i didn't need it before but when i tried to create another example, it just didn't work. Besides, if it's a parameter, why shouldn't use it? Wouldn't it be better to know which template i'm using, specifically?Provisional
S
6

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).

Southwestwardly answered 22/11, 2011 at 15:5 Comment(1)
Hey, thanks thomas, that worked. But why did my first example worked correctly when i didn't pass the template name? it's basically the same checkboxlist. I still don't get what mvc does behind the scenes. By the way, i hope you continue to improve your jqGrid helper.Provisional

© 2022 - 2024 — McMap. All rights reserved.