none
displaying SP Documents in asp.net mvc 5 razor view. RRS feed

  • Question

  • Hi,

    In my Provider Hosted app built on asp.net mvc 5, I am uploading attachments to document library by itemId. Now I need to display the files based on itemId on the Razor view with a "delete" option with each file so that user can delete desired file. I am getting the list of files by itemId in my method but no idea how to design and display on Razor view. Please help me out of this. Here is the method-

    public List<string> getFiles(ClientContext clientContext, int ItemId)
            {
                List<string> docName = new List<string>();
                if (clientContext != null)
                {
                    Web spWeb = clientContext.Web;
                    List docLibrary = spWeb.Lists.GetByTitle("Documents");
                    Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
                    query.ViewXml = "<View>"
                                   + "<Query>"
                                   + "<Where><Eq><FieldRef Name='Request_ID'/><Value Type='Number'>" + ItemId + "</Value></Eq></Where>"
                                   + "</Query>"
                                   + "</View>";
                    ListItemCollection iles = docLibrary.GetItems(query);
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
                    foreach(ListItem doc in files.ToList())
                    {
                        docTitle.Add(doc["FileLeafRef"].ToString());
                    }
                }
                return docName.ToList();                        
            }



    Thursday, October 25, 2018 7:58 AM

Answers

  • Hi,

    Sample demo for your reference.

    [SharePointContextFilter]
            public ActionResult Index()
            {
                User spUser = null;
    
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        spUser = clientContext.Web.CurrentUser;
    
                        clientContext.Load(spUser, user => user.Title);
    
                        clientContext.ExecuteQuery();
    
                        ViewBag.UserName = spUser.Title;
                        var fileList = getFiles(clientContext, 1);
                        ViewBag.FileList = fileList;
                    }
                }
    
                return View();
            }
    
            [HttpPost]
            public string DeleteFile()
            {
                var value1 = Request["fileRef"];
                //to do delete file
                return "Ok";
            }
            public List<string> getFiles(ClientContext clientContext, int ItemId)
            {
                List<string> docName = new List<string>();
                if (clientContext != null)
                {
                    Web spWeb = clientContext.Web;
                    List docLibrary = spWeb.Lists.GetByTitle("MyDoc");
                    Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
                    query.ViewXml = "<View>"
                                   + "<Query>"
                                   + "<Where><Eq><FieldRef Name='Request_ID'/><Value Type='Number'>" + ItemId + "</Value></Eq></Where>"
                                   + "</Query>"
                                   + "</View>";
                    ListItemCollection files = docLibrary.GetItems(query);
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
                    foreach (ListItem doc in files.ToList())
                    {
                        docName.Add(doc["FileLeafRef"].ToString());
                    }
                }
                return docName.ToList();
            }

    index.cshtml:

     <table border="1" id="Filestable"
               class="tableclass"
               style="width:200px">
            <thead>
                <tr>
                    <th>File</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @if (ViewBag.FileList.Count > 0)
                {
                    foreach (var value in ViewBag.FileList)
                    {
                        <tr>
                            <td>@value</td>
                            <td><input id="btnDelete" onclick="DeleteFile(this)" value="Delete" type="button" fileref="@value" /></td>
                        </tr>
                    }
                }
                else
                {
                    <tr><td colspan="2">No files found</td></tr>
                }
            </tbody>
        </table>
    
        @section Scripts {
            @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
            <script type="text/javascript">
                function DeleteFile(obj) {
                    var fileDeleteButtion = $(obj);
                    var fileRef = $(fileDeleteButtion).attr("fileRef");
                    $.ajax({
                        type: "POST",
                        data: "fileRef=" + fileRef,
                        url: '@Url.Action("DeleteFile", "Home")',
                        success: function (data, textStatus, jqXHR) {
                            debugger;
                            if (data == "Ok") {
                                $(fileDeleteButtion).closest('tr').remove();
                            } else {
                                alert('delete file failed');
                            }                        
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            debugger;
                        }
                    });
                }
            </script>
        }

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Friday, October 26, 2018 4:22 AM
  • Hi,

    You could create a class represents a file item, so you could bind other properties as you want.

    Demo:

    Create FileItem.cs in Models.

     public class FileItem
        {
            public string FileName { get; set; }
            public string FileRef { get; set; }
        }

    Bind properties to fileItem.

    [SharePointContextFilter]
            public ActionResult Index()
            {
                User spUser = null;
    
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        spUser = clientContext.Web.CurrentUser;
    
                        clientContext.Load(spUser, user => user.Title);
    
                        clientContext.ExecuteQuery();
    
                        ViewBag.UserName = spUser.Title;
                        var fileList = getFiles(clientContext, 1);
                        ViewBag.FileList = fileList;
                    }
                }
    
                return View();
            }
    
            [HttpPost]
            public string DeleteFile()
            {
                var value1 = Request["fileRef"];
                //to do delete file
                return "Ok";
            }
            public List<FileItem> getFiles(ClientContext clientContext, int ItemId)
            {
                List<FileItem> docName = new List<FileItem>();
                if (clientContext != null)
                {
                    Web spWeb = clientContext.Web;
                    List docLibrary = spWeb.Lists.GetByTitle("MyDoc");
                    Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
                    query.ViewXml = "<View>"
                                   + "<Query>"
                                   + "<Where><Eq><FieldRef Name='Request_ID'/><Value Type='Number'>" + ItemId + "</Value></Eq></Where>"
                                   + "</Query>"
                                   + "</View>";
                    ListItemCollection files = docLibrary.GetItems(query);
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
                    foreach (ListItem doc in files.ToList())
                    {
                        FileItem file = new FileItem();
                        file.FileName = string.Format("{0}", doc["FileLeafRef"]);
                        file.FileRef = string.Format("{0}", doc["FileRef"]);
                        docName.Add(file);
                    }
                }
                return docName;
            }

    Bind with Razor view.

    <table border="1" id="Filestable"
               class="tableclass"
               style="width:200px">
            <thead>
                <tr>
                    <th>File</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @if (ViewBag.FileList.Count > 0)
                {
                    foreach (var value in ViewBag.FileList)
                    {
                        <tr>
                            <td>@value.FileName</td>
                            <td><input id="btnDelete" onclick="DeleteFile(this)" value="Delete" type="button" fileref="@value.FileRef" /></td>
                        </tr>
                    }
                }
                else
                {
                    <tr><td colspan="2">No files found</td></tr>
                }
            </tbody>
        </table>

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • Marked as answer by pointtoshare Friday, October 26, 2018 6:40 AM
    Friday, October 26, 2018 6:27 AM

All replies

  • Hi,

    Sample demo for your reference.

    [SharePointContextFilter]
            public ActionResult Index()
            {
                User spUser = null;
    
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        spUser = clientContext.Web.CurrentUser;
    
                        clientContext.Load(spUser, user => user.Title);
    
                        clientContext.ExecuteQuery();
    
                        ViewBag.UserName = spUser.Title;
                        var fileList = getFiles(clientContext, 1);
                        ViewBag.FileList = fileList;
                    }
                }
    
                return View();
            }
    
            [HttpPost]
            public string DeleteFile()
            {
                var value1 = Request["fileRef"];
                //to do delete file
                return "Ok";
            }
            public List<string> getFiles(ClientContext clientContext, int ItemId)
            {
                List<string> docName = new List<string>();
                if (clientContext != null)
                {
                    Web spWeb = clientContext.Web;
                    List docLibrary = spWeb.Lists.GetByTitle("MyDoc");
                    Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
                    query.ViewXml = "<View>"
                                   + "<Query>"
                                   + "<Where><Eq><FieldRef Name='Request_ID'/><Value Type='Number'>" + ItemId + "</Value></Eq></Where>"
                                   + "</Query>"
                                   + "</View>";
                    ListItemCollection files = docLibrary.GetItems(query);
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
                    foreach (ListItem doc in files.ToList())
                    {
                        docName.Add(doc["FileLeafRef"].ToString());
                    }
                }
                return docName.ToList();
            }

    index.cshtml:

     <table border="1" id="Filestable"
               class="tableclass"
               style="width:200px">
            <thead>
                <tr>
                    <th>File</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @if (ViewBag.FileList.Count > 0)
                {
                    foreach (var value in ViewBag.FileList)
                    {
                        <tr>
                            <td>@value</td>
                            <td><input id="btnDelete" onclick="DeleteFile(this)" value="Delete" type="button" fileref="@value" /></td>
                        </tr>
                    }
                }
                else
                {
                    <tr><td colspan="2">No files found</td></tr>
                }
            </tbody>
        </table>
    
        @section Scripts {
            @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
            <script type="text/javascript">
                function DeleteFile(obj) {
                    var fileDeleteButtion = $(obj);
                    var fileRef = $(fileDeleteButtion).attr("fileRef");
                    $.ajax({
                        type: "POST",
                        data: "fileRef=" + fileRef,
                        url: '@Url.Action("DeleteFile", "Home")',
                        success: function (data, textStatus, jqXHR) {
                            debugger;
                            if (data == "Ok") {
                                $(fileDeleteButtion).closest('tr').remove();
                            } else {
                                alert('delete file failed');
                            }                        
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            debugger;
                        }
                    });
                }
            </script>
        }

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Friday, October 26, 2018 4:22 AM
  • Hi Lee,

    Thanks for this example, it is workable.

    One thing, the @value shows only the file name text, is it possible to get the file name with link?

    Thanks.

    Friday, October 26, 2018 5:40 AM
  • Hi,

    You could create a class represents a file item, so you could bind other properties as you want.

    Demo:

    Create FileItem.cs in Models.

     public class FileItem
        {
            public string FileName { get; set; }
            public string FileRef { get; set; }
        }

    Bind properties to fileItem.

    [SharePointContextFilter]
            public ActionResult Index()
            {
                User spUser = null;
    
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        spUser = clientContext.Web.CurrentUser;
    
                        clientContext.Load(spUser, user => user.Title);
    
                        clientContext.ExecuteQuery();
    
                        ViewBag.UserName = spUser.Title;
                        var fileList = getFiles(clientContext, 1);
                        ViewBag.FileList = fileList;
                    }
                }
    
                return View();
            }
    
            [HttpPost]
            public string DeleteFile()
            {
                var value1 = Request["fileRef"];
                //to do delete file
                return "Ok";
            }
            public List<FileItem> getFiles(ClientContext clientContext, int ItemId)
            {
                List<FileItem> docName = new List<FileItem>();
                if (clientContext != null)
                {
                    Web spWeb = clientContext.Web;
                    List docLibrary = spWeb.Lists.GetByTitle("MyDoc");
                    Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
                    query.ViewXml = "<View>"
                                   + "<Query>"
                                   + "<Where><Eq><FieldRef Name='Request_ID'/><Value Type='Number'>" + ItemId + "</Value></Eq></Where>"
                                   + "</Query>"
                                   + "</View>";
                    ListItemCollection files = docLibrary.GetItems(query);
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
                    foreach (ListItem doc in files.ToList())
                    {
                        FileItem file = new FileItem();
                        file.FileName = string.Format("{0}", doc["FileLeafRef"]);
                        file.FileRef = string.Format("{0}", doc["FileRef"]);
                        docName.Add(file);
                    }
                }
                return docName;
            }

    Bind with Razor view.

    <table border="1" id="Filestable"
               class="tableclass"
               style="width:200px">
            <thead>
                <tr>
                    <th>File</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @if (ViewBag.FileList.Count > 0)
                {
                    foreach (var value in ViewBag.FileList)
                    {
                        <tr>
                            <td>@value.FileName</td>
                            <td><input id="btnDelete" onclick="DeleteFile(this)" value="Delete" type="button" fileref="@value.FileRef" /></td>
                        </tr>
                    }
                }
                else
                {
                    <tr><td colspan="2">No files found</td></tr>
                }
            </tbody>
        </table>

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • Marked as answer by pointtoshare Friday, October 26, 2018 6:40 AM
    Friday, October 26, 2018 6:27 AM