I have a list of items I'm reading out of sitecore and looping in my View. The items are quite stright forward and are simply output as a series of <li>
[SitecoreType(AutoMap = true)]
public class Model
{
[SitecoreId]
public Guid Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public string Path { get; set; }
[SitecoreField]
public virtual string TabText { get; set; }
}
I use the model above in a
public class ViewModel
{
public List<Model> Models {get; set;}
}
I'm struggling to consume this view model in my view though and use glassmappers Editable
feature:
@using Sitecore.Mvc
@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<ViewModel>
<ul>
@for (int specCounter = 0; specCounter < Model.Models.Count; specCounter++)
{
<!--@specCounter-->
<li>
@Editable(e => e.Models[specCounter].TabText)</li>
}
</ul>
this results in a series of errors being written into the resuting HTML:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) at lambda_method(Closure , SpecificationInDetailViewModel ) at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression
1 field, Expression
1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer) Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
If I remove the Editable
call then the <li>
are output correctly. If I use a foreach
loop (as opposed to a for
loop):
@using Sitecore.Mvc
@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<ViewModel>
<ul>
@foreach (var model in Model.Models)
{
<!--@specCounter-->
<li>
@Editable(e => model.TabText)</li>
}
</ul>
then all the <li>
contains the text from the last Model (obviously some kind of pass by reference issue). Again removing Editable
produces the correct result.
Is there any work around for this? I want these items to be editable in the experience viewer.
You should pass the target Glass Item as a first parameter to the Editable
:
@for (int specCounter = 0; specCounter < Model.Models.Count; specCounter++)
{
<!--@specCounter-->
<li>
@Editable(Model.Models[specCounter], e => e.TabText)</li>
}
or foreach
:
@foreach (var model in Model.Models)
{
<!--@specCounter-->
<li>
@Editable(model, e => e.TabText)</li>
}
For more information, check Glass Tutotial - MVC Page Editor Support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With