Monday, June 20, 2016

JavaScript in Application Pages - Farm Solution Deployment

Below examples shows deploying an application page that contains JavaScript using Farm solution deployment approach.

I am creating an empty SharePoint project in Visual Studio. Next I had added application page with Name 'JSDemo.aspx'. Below is the folder structure for the project.

 

 In Application page, I had created input button with click action, Essentially when I click the button I am loading all the lists present in the site that has an item count greater than 0.

I had used sp.js to create context for this specific site that is declared in ScriptLink tag in the application page. Below is the complete code.

[code]
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <SharePoint:ScriptLink Name="sp.js" LoadAfterUI="true" runat="server" Localizable="false" ></SharePoint:ScriptLink>

    <%--load intellisense for sp.js--%>
    <% #if ZZZZ %>
    <script type="text/javascript" src="/_layouts/SP.debug.js"></script>
    <% #endif %>

    <script type="text/javascript">
        var lists;
        function getLists() {
            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            context.load(web, "Title", "Description");
            lists = web.get_lists();
            context.load(lists, "Include(Title,ItemCount)");
            context.executeQueryAsync(onSuccess,onFail);
        }

        function onSuccess() {
            var ul = document.getElementById("listitems");
            var listsEnum = lists.getEnumerator();
            while (listsEnum.moveNext()) {
                var list = listsEnum.get_current();
                if (list.get_itemCount() > 0) {
                    var title = list.get_title();
                    var elem = document.createElement("li");
                    elem.innerText = title;
                    ul.appendChild(elem);
                }
            }
        }

        function onFail() {
            alert("Request Failed");
        }
    </script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<input id="getListsButton" type="button" value="Get List items" onclick="getLists()" />
<br />
<br />
<ul id="listitems"></ul>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>
[/code]

Result: For accessing the application page I am navigating to /_layout/JSApplicationPage/JSDemo.aspx page

No comments:

Post a Comment