0

I have an MVC app and am trying to recreate a Lookup site column on a page with a drop down list (add all the choices to the list). The itemColl ends up being empty, is there something that I'm not loading correctly?

SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
ClientContext clientContext = spContext.CreateUserClientContextForSPHost();
Field field = clientContext.Web.Fields.GetByInternalNameOrTitle('InternalName');

clientContext.Load(field);
clientContext.ExecuteQuery();

FieldLookup lkField = clientContext.CastTo<FieldLookup>(field);
clientContext.Load(lkField, f => f.LookupList);
clientContext.ExecuteQuery();

var list = clientContext.Web.Lists.GetById(new Guid(lkField.LookupList));

var itemColl = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(itemColl, items => items.Include(listItem => listItem[lkField.LookupField]));
clientContext.Load(itemColl);
clientContext.ExecuteQuery();

1 Answer 1

0

You have to hack into the schema of the field:

ctx.Load(field, (s) => s.SchemaXml);
ctx.ExecuteQuery();
var lookupListId = XElement.Parse(field.SchemaXml)
                              .Attributes()
                              .First(s => s.Name == "List")
                              .Value;

See: Convert Field To FieldLookup using ClientContext

3
  • I was able to get around the issue by changing to CastTo instead of as (8th line). I am still not able to actually get any items though (itemColl is empty). Do you know if there's something else I'm not loading to the context correctly?
    – cooper
    Commented May 11, 2017 at 19:16
  • My only other thought was to target your SP List based field, versus your Web fields collection, but that might be a red herring.
    – InvoiceGuy
    Commented May 11, 2017 at 21:03
  • I just figured it out actually, I didn't have the right permissions in my app to access the list. Can't believe I missed that
    – cooper
    Commented May 11, 2017 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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