Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Glass mapper Editable() with List<> items not working?

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>

Model

[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

Viewmodel

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:

View

@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](Expression1 field, Expression1 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.

like image 414
Liam Avatar asked Feb 08 '23 22:02

Liam


1 Answers

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.

like image 88
Marek Musielak Avatar answered Feb 10 '23 10:02

Marek Musielak