Explore the Experience in SharePoint 2013

Wednesday, February 4, 2015

Get Site Name using ECMAScript very quickly and easily

No comments

Hi Friends ,

Thanks for Visiting my blog.

In my previous post , I was described about  ECMAScript Client Object Model.

In this Post ,I would  like to describe How we can get the Site Title through ECMAScript ?.

Please find the below steps to achieve this Site Title  .

1. Open Visual Studio -->Create an Empty Project (Farm Solution) -->Create Visual web Part

2. Add the   below script files refernces in  UserControl.ascx

  <Script src="//code.jquery.com/jquery-1.10.2.js"></script>
 <SharePoint:ScriptLink ID="ScriptLink1" Name="SP.js" runat="server" OnDemand="true" 
    Localizable="false" />

3. Add the Below Script   UserControl.ascx

<script type="text/ecmascript">
      function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        ctx.load(this.web);
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
        alert('web title:' + this.web.get_title());
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:' + args.get_message());
    }
</script>

Below is the Screen Shot of Visual Web part after we  done with Scripting inside the ascx.




4 . Deploy the Solution to SharePoint Site .

5. Navigate to the SharePoint Site in which you want Place the Web Part .

6. Add  Web Part in your Page and click on the button . You will be able to see the Web Site Title .





This is how , we get the Site Name very easily using ECMAScript with minimal Scripting.

Description about Script 


1. var ctx = new SP.ClientContext.get_current();
     
     Getting the Current Site Collection Context

2.  this.web = ctx.get_web();

   Getting the Current Web Context.

3.  ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));

        executeQueryAsync

                Executes the current pending request asynchronously on the server.

               The executeQueryAsync method is inherited from the SP.ClientRuntimeContext object.                      This virtual method is asynchronous, which means that the code will continue to be                              executed without waiting for the server to respond.
            onSuccess
             A function or a delegate of the method to call if the request executes successfully. 
            onFail
            A function or a delegate of the method to call if the request fails to execute.


Hope this post is useful...

Thanks 

No comments :

Post a Comment