Sunday, 11 October 2015

Add List Item in SharePoint List Using JavaScript


Step 1
Create a Web Part using Visual Studio 2013.

Create a Web Part using Visual Studio

Step 2
Open the ascx (MyFirstWebPartUserControl.ascx) and design your UI. Here I have created Employee details information.

Employee details information

The following  is the design part of the code:
  1. <div>  
  2.     <table cellpadding="10">  
  3.         <tr>  
  4.             <td colspan="2" align="center">  
  5.                 <label style="width: 200px; height: 50px; font-size: large; font: bold;">Employee Details</label>  
  6.             </td>  
  7.         </tr>  
  8.         <tr>  
  9.             <td>  
  10.                 <label style="width: 100px; height: 50px; font-size: large; font: bold;">Employee ID</label>  
  11.             </td>  
  12.             <td>  
  13.                 <input type="text" id="txtEmployeeId" style="width: 100px;" />  
  14.             </td>  
  15.         </tr>  
  16.         <tr>  
  17.             <td>  
  18.                 <label style="width: 100px; height: 50px; font-size: large; font: bold;">First Name</label></td>  
  19.             <td>  
  20.                 <input type="text" id="txtFirstName" style="width: 100px;" /></td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>  
  24.                 <label style="width: 100px; height: 50px; font-size: large; font: bold;">Last Name</label></td>  
  25.             <td>  
  26.                 <input type="text" id="txtLastName" style="width: 100px;" /></td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>  
  30.                 <label style="width: 100px; height: 50px; font-size: large; font: bold;">State</label></td>  
  31.             <td>  
  32.                 <input type="text" id="txtState" style="width: 100px;" /></td>  
  33.         </tr>  
  34.         <tr>  
  35.             <td>  
  36.                 <label style="width: 100px; height: 50px; font-size: large; font: bold;">City</label></td>  
  37.             <td>  
  38.                 <input type="text" id="txtCity" style="width: 100px;" /></td>  
  39.         </tr>  
  40.         <tr>  
  41.             <td>  
  42.                 <input type="button" id="btnSave" value="Save" onclick="createListItem();" />  
  43.   
  44.             </td>  
  45.             <td>  
  46.                 <input type="button" id="btnCancel" value="Cancel" onclick="ClearFields();" />  
  47.             </td>  
  48.         </tr>  
  49.     </table>  
  50.   
  51. </div> 
The following  is the JavaScript Code:
  1. <script type="text/javascript">  
  2.     var siteUrl = 'http://ils-jacobr:35526';  
  3.   
  4.     function createListItem() {  
  5.         var empId = document.getElementById('txtEmployeeId').value;  
  6.         var firstName = document.getElementById('txtFirstName').value;  
  7.         var lastName = document.getElementById('txtLastName').value;  
  8.         var state = document.getElementById('txtState').value;  
  9.         var city = document.getElementById('txtCity').value;  
  10.         var clientContext = new SP.ClientContext(siteUrl);  
  11.         var oList = clientContext.get_web().get_lists().getByTitle('EmployeeDetails');  
  12.         var itemCreateInfo = new SP.ListItemCreationInformation();  
  13.         this.oListItem = oList.addItem(itemCreateInfo);  
  14.         oListItem.set_item('EmployeeID', empId);  
  15.         oListItem.set_item('FirstName', firstName);  
  16.         oListItem.set_item('LastName', lastName);  
  17.         oListItem.set_item('City', city);  
  18.         oListItem.set_item('State', state);  
  19.         oListItem.update();  
  20.         clientContext.load(oListItem);  
  21.         clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));  
  22.     }  
  23.   
  24.     function onQuerySucceeded() {  
  25.   
  26.         alert('Item created Successfully !!!!');  
  27.         document.getElementById('txtCity').value = "";  
  28.         document.getElementById('txtEmployeeId').value = "";  
  29.         document.getElementById('txtFirstName').value = "";  
  30.         document.getElementById('txtLastName').value = "";  
  31.         document.getElementById('txtState').value = "";          
  32.     }  
  33.   
  34.     function onQueryFailed(sender, args) {  
  35.   
  36.         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  37.     }  
  38.     function ClearFields() {  
  39.         document.getElementById('txtCity').value = "";  
  40.         document.getElementById('txtEmployeeId').value = "";  
  41.         document.getElementById('txtFirstName').value = "";  
  42.         document.getElementById('txtLastName').value = "";  
  43.         document.getElementById('txtState').value = "";  
  44.     }  
  45. </script> 
Step 3
Build and deploy your the solution.

Deploy

Step 4
Go to your SharePoint site and create one page under site pages. Add your web part to that page.

Add your web part in that page

Step 5
Enter the Employee details and click the Save button.

Employee details

click save button

Step 6
Go to your List and the item will display.

display

Add a Custom Search Link to Your Search Results Page in SharePoint 2013 


Search Verticals
In SharePoint 2013, there are four default search verticals displayed in the Enterprise Search Center as shown below. They are placed in the Search Navigation Web Part.

Search Navigation Web Part

When the user clicks on each vertical they are redirected to one of the following search pages:
All these results pages are available in the pages library. The Search Results Web Part are configured to use different result sources in these pages.

Search Results Web Part

The following describes how to create a search results page:
  1. Navigate to the Enterprise Search Site:https://c986.sharepoint.com/sites/Test/Enterprise%20Search/.
  2. Click on Site Actions and then click on Site Contents.

    Site Contents
  3. Click on the Pages app.

    Pages app
  4. Click on the Files tab in the ribbon interface, select Page from the New Document drop down.

    New Document
  5. Enter the Title, Description and URL for the page. Click on the Create button.

    Click on Create
  6. The Search Page (custom.aspx) is created successfully.

    Search Page custom
The following is how to create a search vertical:
  1. Click on Site Actions and then click on Site Settings.
  2. Click on Search Settings available in the Search section.

    Search Settings
  3. On the Configure Search Navigation section, click on the Add link.

    Configure Search Navigation
  4. Enter the Title and the URL (the URL of the results page we have created in the previous section).
  5. Click on the OK button.

    Click on Ok button
  6. Click on the OK button on the search settings page.
Testing
  1. Navigate to the Search default page:https://c986.sharepoint.com/sites/Test/Enterprise%20Search/Pages/default.aspx.
  2. Search for some keyword and it will be redirected to results.aspx page. You will see a new search vertical that we created.

    redirected to results
  3. Click on Custom, it will be redirected to the custom.aspx page.

    Note: You can edit the search results web part and configure your custom query on the custom.aspx page.

    Custom

News Rollup WebPart in SharePoint 2013


Open SharePoint Site.

Open SharePoint Site

Create a simple list named “News”.

Create a simple list

Open Visual studio.

Create a new SharePoint 2013 empty project.

Add a visual webpart into the SharePoint solution named “News rollup”.

visual studio

news

Now add a repeater control into the News Rollup.ascx.

Code:
  1. <asp:Repeater ID="rptsmartspeak" runat="server">  
  2.    <ItemTemplate>  
  3.           
  4.         <%#DataBinder.Eval(Container.DataItem,"Date")%>   
  5.         <br />  
  6.         <h2 style="padding-top: 5px; font-weight: 700; font-size: 12px;"><%#DataBinder.Eval(Container.DataItem,"Title")%></h2>  
  7.         <br />  
  8.         <br />  
  9.         <p  style="margin-top: -39px;">  
  10.             <%#FormatDescription(Container.DataItem,"Description")%>  
  11.                                       
  12.         </p>  
  13.        <hr />  
  14.     </ItemTemplate>  
  15. </asp:Repeater>  
Code

To bind the data into the repeater from SharePoint lists.

Download CAML Query builder.

Click here to download U2U CAML Query builder.

After installation, I am going to generate a query to retrieve the Isactive values from the news list.

retrieve the Isactive values

Code
  1. using Microsoft.SharePoint;  
  2. using System;  
  3. using System.ComponentModel;  
  4. using System.Web.UI.WebControls.WebParts;  
  5.   
  6. namespace News.News_Rollup  
  7. {  
  8.     [ToolboxItemAttribute(false)]  
  9.     public partial class News_Rollup : WebPart  
  10.     {  
  11.         // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution  
  12.         // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready  
  13.         // for production. Because the SecurityPermission attribute bypasses the security check for callers of  
  14.         // your constructor, it's not recommended for production purposes.  
  15.         // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]  
  16.         public News_Rollup()  
  17.         {  
  18.         }  
  19.   
  20.         protected override void OnInit(EventArgs e)  
  21.         {  
  22.             base.OnInit(e);  
  23.             InitializeControl();  
  24.         }  
  25.   
  26.         protected void Page_Load(object sender, EventArgs e)  
  27.         {  
  28.             if(!Page.IsPostBack)  
  29.             {  
  30.                 Bindspeaker();  
  31.             }  
  32.         }  
  33.         private void Bindspeaker()  
  34.         {  
  35.             using (SPSite site = new SPSite(SPContext.Current.Site.Url))  
  36.             {  
  37.                 using (SPWeb web = site.OpenWeb())  
  38.                 {  
  39.                     SPList list = web.Lists["News"];  
  40.                     if (list != null)  
  41.                     {  
  42.                         SPQuery query = new SPQuery();  
  43.                         query.Query = "<Where><Eq><FieldRef Name='Isactive' /><Value Type='Boolean'>1</Value></Eq></Where>";  
  44.                         SPListItemCollection collitem = list.GetItems(query);  
  45.   
  46.                         rptsmartspeak.DataSource = collitem.GetDataTable();  
  47.                         rptsmartspeak.DataBind();  
  48.   
  49.                     }  
  50.                 }  
  51.             }  
  52.         }  
  53.     }  
  54. }  
Now I am going to do some customization of my repeater control to view the news stylish.

Full code
News Rollup.ascx
  1. <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>  
  2. <%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>   
  3. <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>   
  4. <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  5. <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>  
  6. <%@ Import Namespace="Microsoft.SharePoint" %>   
  7. <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  8. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="News Rollup.ascx.cs" Inherits="News.News_Rollup.News_Rollup" %>  
  9. <div style="height:150px; width:200px" >  
  10. <table  style="width:100%" >  
  11.     <tr>  
  12.         <td  style="width:10%" ></td>  
  13.         <td  style="width:80%" >  
  14.              <marquee  behavior="scroll" direction="up" scrollamount="3" onmouseover="stop();"  onmouseout="start()";>  
  15.     <div class="smartspeak" style="padding-right: 20px; height:300px; width:280px;">  
  16.  <asp:Repeater ID="rptsmartspeak" runat="server">  
  17.                    <ItemTemplate>  
  18.                           
  19.                         <%#DataBinder.Eval(Container.DataItem,"Date")%>   
  20.                         <br />  
  21.                         <h2 style="padding-top: 5px; font-weight: 700; font-size: 12px;"><%#DataBinder.Eval(Container.DataItem,"Title")%></h2>  
  22.                         <br />  
  23.                         <br />  
  24.                         <p  style="margin-top: -39px;">  
  25.                             <%#FormatDescription(Container.DataItem,"Description")%>  
  26.                                                       
  27.                         </p>  
  28.                        <hr />  
  29.                     </ItemTemplate>  
  30.                 </asp:Repeater>  
  31.          </div>         
  32.         </marquee>  
  33.           </td>  
  34.         <td  style="width:10%" ></td>  
  35.   
  36.     </tr>  
  37. </table>  
News Rollup.ascx.cs
  1. using Microsoft.SharePoint;  
  2. using System;  
  3. using System.ComponentModel;  
  4. using System.Web.UI;  
  5. using System.Web.UI.WebControls.WebParts;  
  6.   
  7. namespace News.News_Rollup  
  8. {  
  9.     [ToolboxItemAttribute(false)]  
  10.     public partial class News_Rollup : WebPart  
  11.     {  
  12.         // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution  
  13.         // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready  
  14.         // for production. Because the SecurityPermission attribute bypasses the security check for callers of  
  15.         // your constructor, it's not recommended for production purposes.  
  16.         // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]  
  17.         public News_Rollup()  
  18.         {  
  19.         }  
  20.   
  21.         protected override void OnInit(EventArgs e)  
  22.         {  
  23.             base.OnInit(e);  
  24.             InitializeControl();  
  25.         }  
  26.   
  27.         protected void Page_Load(object sender, EventArgs e)  
  28.         {  
  29.             if (!Page.IsPostBack)  
  30.             {  
  31.                 Bindspeaker();  
  32.             }  
  33.         }  
  34.         private void Bindspeaker()  
  35.         {  
  36.             using (SPSite site = new SPSite(SPContext.Current.Site.Url))  
  37.             {  
  38.                 using (SPWeb web = site.OpenWeb())  
  39.                 {  
  40.                     SPList list = web.Lists["News"];  
  41.                     if (list != null)  
  42.                     {  
  43.                         SPQuery query = new SPQuery();  
  44.                         query.Query = "<Where><Eq><FieldRef Name='Isactive' /><Value Type='Boolean'>1</Value></Eq></Where>";  
  45.                         SPListItemCollection collitem = list.GetItems(query);  
  46.   
  47.                         rptsmartspeak.DataSource = collitem.GetDataTable();  
  48.                         rptsmartspeak.DataBind();  
  49.   
  50.                     }  
  51.                 }  
  52.             }  
  53.         }  
  54.         protected string FormatDescription(object item, string fieldName)  
  55.         {  
  56.             if (string.IsNullOrEmpty(DataBinder.Eval(item, fieldName).ToString()))  
  57.             {  
  58.                 return string.Empty;  
  59.             }  
  60.             else  
  61.             {  
  62.                 string text = DataBinder.Eval(item, fieldName).ToString();  
  63.                 if (text.Length < 250)  
  64.                     return string.Format("{0}", text);  
  65.                 return string.Format("{0}", text.Substring(0, 250));  
  66.             }  
  67.         }  
  68.   
  69.     }  
  70. }  
Now deploy the solution.

After deploying, the webpart adds some news contents into the SharePoint list.

deploy  

SharePoint list

The final result is.

result