简体   繁体   中英

'Title' field initialization error in SharePoint online add-in

I'm trying to write a SharePoint add-in which has a part that has to assign the name of a selected file in "Documents" list to a string called title.

    protected void Page_Load(object sender, EventArgs e)
    {

        var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

        int listItemID;

        listItemID = GetListItemIDFromQueryParameter();

        using (var clientContext = spContext.CreateUserClientContextForSPHost())
        {
            clientContext.Load(clientContext.Web,
            web => web.Title,
            web => web.CurrentUser,
            web => web.Lists);

            List doclist = clientContext.Web.Lists.GetByTitle("Documents");
            Microsoft.SharePoint.Client.ListItem item = doclist.GetItemById(listItemID);

            string title = item.File.Title;
        }
    }

Function GetListItemIDFromQueryParametr(); works like intended - it returns an ID int value of the selected file. I want to get the file's name by that ID. The following code returns an error -

Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException: 'The property or field 'Title' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'

I am now trying to figure out how to initialize that field, but so far I haven't found anything that would help me. Any clues would be much appreciated.

You haven't loaded your listitem yet. Before you can read properties in csom you need to load them, like how you have loaded your web. You also need to execute the queries you load which you haven't done.

Add a clientContext.ExecuteQuery(); after the line where you initialise do list

Apologies for poor formatting, I'm on a mobile device

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM