3

I was working on a project that needed some data passed on through the context. Logic was implemented based on https://jss.sitecore.com/docs/techniques/extending-layout-service/layoutservice-extending-context.

My question is that is it possible to have a list of objects bassed on to the context? I wanted the SitecoreContext to end up like:

sitecoreContext:{
   items: [
   {
     field1: ob1Field.Value,
     field2: ob1Field2Value2
   },
   {
     field1: ob2.Field.Value,
     field2: ob2Field2Value2
   }
   ...
   ]
}

UPDATE Thanks to Arvind's answer.

Here is the working code:

Item[] items = Sitecore.Context.Database.SelectItems("myQuery");
var itemList = new List<dynamic>();
foreach (Item i in items)
{
   itemList.Add(new
   {
     field1 = i.Fields["field1"]?.Value,
     field2 = i.Fields["field2"]?.Value
   }
}
args.ContextData.Add("items", itemList);
1

This can be done in following way.

protected override void DoProcess(GetLayoutServiceContextArgs args, AppConfiguration application)
{
    args.ContextData.Add("items", new[]
        {
            new {
                field1 = "field1Value",
                field2 = "field2Value" 
            },
            new {
                field1 = "field1Value",
                field2 = "field2Value"
            }
        }
    );
}

I haven't tested this code but it should work. Let me know if you face any challenges implementing it.

6
  • Perfect, it works as needed! Is there a way to append a new object after that? I tried with args.ContextData["items"].Append(new {field1 = "foo, field2="foo2}); but it throws an error that 'object' does not contain a definition for 'Append' – coolzoa Mar 4 at 16:22
  • You can add a new object right in the array itself if it is required. – Arvind Gehlot Mar 4 at 16:29
  • Also requesting you to accept the answer for your original question, if it works for you. – Arvind Gehlot Mar 4 at 16:36
  • Yup, many thanks! When you say 'add into the array itself', do you mean inside the new[]{} just like the two others? Because I need to append a new object after a certain call to get another item. – coolzoa Mar 4 at 16:47
  • In that case you can create a generic list, add items into that list after a certain call and then finally add that list into context data at the end after converting it into array. If this is not clear to you? Please post another question with the proper details and i would be happy to look into that. Please upvote the answer as well if u like. – Arvind Gehlot Mar 4 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.