Question

Hi I want to display a list of documents in an MVC view and be able to download them on click. I have attempted a solution myself as shown below. I have been struggling with this for a long time so any suggestions will be appreciated.

namespace SharePointMVC.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
            DefaultModel Lists = new DefaultModel();
            string siteURL = "http://MYSPSSITE";
            string documentListName = "MY DOCUMENT LIBRARY";
            ListItemCollection listItems = null;
            using (ClientContext clientContext = new ClientContext(siteURL))
            {
                List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

                CamlQuery camlQuery = new CamlQuery(); ;
                camlQuery.ViewXml =
                    @"<View>

                     <Query>
                     <Where>
                     <Eq>
                     <FieldRef Name ='" + name + @"'/>

                     <Value Type ='" + type + "'>" + value + @"</Value>
                     </Eq>

                     </Where>
                     <RowLimit>" + rowLimit.ToString() + @"</RowLimit>

                     </Query>
                     </View>";

                listItems = documentsList.GetItems(camlQuery);

                clientContext.Load(documentsList);
                clientContext.Load(listItems);

                clientContext.ExecuteQuery();

            }

            return listItems;
        }

        private static ListItem GetDocumentFromSP(String documentName)
        {
            ListItemCollection listItems = GetListItemCollectionFromSP("FileLeafRef", documentName, "Text", 1);
            return (listItems != null && listItems.Count == 1) ? listItems[0] : null;
        }

        public Stream DownloadDocument(string SiteURL, string documentName)
        {
            ListItem item = GetDocumentFromSP(documentName);
            if (item != null)
            {
                using (ClientContext clientContext = new ClientContext(SiteUrl))
                {
                    FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, item["Outline.docx"].ToString());
                    return fileInformation.Stream;
                }
            }

            return null;
        }
Was it helpful?

Solution

If you don't have too many requirements (e.g. must be able to override the magical 5000 documents mark), you could use SPMetal and just run a LINQ query. Do note that it has limitations and isn't as performant as CAML Queries, but it works all the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top