SharePoint client Object Model (I) ECMA Script

Source: Internet
Author: User

The so-called client object model is to call the WCF Service behind it to provide data. In order to reduce the data access volume, data packets use JSON, we can also see that the design of the object model also adds a lot of considerations for reducing the amount of data traffic. There is nothing new in technology. You need to be willing to implement similar functions in SharePoint2007. Of course, it is convenient for us to use many of them.

 
Three types of. NET hosting, ECMA scripts, and SilverLightClient.

This article describes how to use. NET hosted code to access the SharePoint object model.

Notes for ECMAScript Client OM

  • ECMAScript can only be used in SharePoint sites. ECMAScript cannot be used in other Asp. NET sites to access SharePoint site resources or cross-SharePoint sites;
  • JQuery and ECMAScript do not conflict with each other;
  • For security updates, add <SharePoint: FormDigest runat = "server"/>
  • In the code that you will see later, you can specify the content to be loaded to reduce the volume of loaded data, such as client. context. load (this. web, 'title', 'id', 'created '). The attribute value names here use the same system as CAML and are case sensitive;
  • To ensure that your code is called after SP. JS is loaded, you can use ExecuteOrDelayUntilScriptLoaded (myjsFunction, "sp. js ").

Let's look at a Simple Matching Relationship Between SharePoint OM and client OM:

Server OM Client OM
SPContext ClientContext
SPSite Site
SPWeb Web
SPList List
SPListItem ListItem
SPField Field

Let's take a look at the final result. It is a preliminary plan function. It mainly designs the creation, query, and management of the list, and also involves the Case of uploading files, in the future, if there are any important items, they will be added gradually.

The link in will call the UI Javascript interface to create the SharePoint2010 pop-up window. The background page of the pop-up window is located in the SitePage document library. Please note that this is only applicable to the WebPart page, if it is not enabled, an error will be reported: "The Ribbon Tab with id:" Ribbon. read "has not been made available for this page or does not exist ".

(Note: This Page will not be used later. It is only used to explain Ribbon)

Creation list:

First, add the following two Script links through Designer:

<SharePoint: ScriptLink Name = "SP. js" runat = "server" OnDemand = "true" Localizable = "false"/>
<SharePoint: ScriptLink Name = "SP. debug. js" runat = "server" OnDemand = "true" Localizable = "false"/>

ECMAScriptOM and. NET Managed ClientOM (will be discussed later) are similar, but there are also several points to note:

  1. Server URLs cannot be used in ClientContext;
  2. Does not support LINQ;
  3. Essentially, ECMAScript OM is asynchronous.

The code is very simple and easy to understand. There is a fun thing in it: SP. UI. Notify. addNotification. Through this class, you can display the prompt message in the call screen, which is very SharePoint.

The demo result is as follows:

Enter the List name in the text box and click "Create List". After the List is generated, the system prompts "List test1 created" in the upper right corner. In this example, annoucement is used as the List type.

The source code is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var messageId;
Function createList (listName ){
Var clientContext = new SP. ClientContext ();
Var oWebSite = clientContext. get_web ();
Var listCreationInfo = new SP. ListCreationInformation ();
ListCreationInfo. set_title (listName );
ListCreationInfo. set_templateType (SP. ListTemplateType. announcements );
ListCreationInfo. set_quickLaunchOption (SP. QuickLaunchOptions. on );
Var oList = oWebSite. get_lists (). add (listCreationInfo );
ClientContext. load (oList );
ClientContext.exe cuteQueryAsync (Function. createDelegate (this, this. onQuerySucceeded), Function. createDelegate (this, this. onQueryFailed ));
}
Function onQuerySucceeded (){
// Remove the 'creating' event notification
If (messageId! = Null)
{
SP. UI. Y. removeNotification (messageId );
}
// Add 'created' notification as non sticky
MessageId = SP. UI. policy. addNotification ("List <B>" + oList. get_title () + "</B> created... ", false," ", null );
}

Function onQueryFailed (sender, args ){
// Remove the 'creating' event notification
If (messageId! = Null)
{
SP. UI. Y. removeNotification (messageId );
}
// Shown in case of error on the js om call
MessageId = SP. UI. Policy. addNotification ("Operation was canceled...", false, "", null );
}

</Script>

Get all lists:

Similarly, let's take a look at the effect. Click "Get All List" to read All the lists on the current site and set the hyperlink attribute of the response, click "Hide List" to Hide it (actually a Div)

The code is very straightforward. It only describes one vertex. The use of JavaScript functions such as getEnumerator (), moveNexst (), and get_current () provides a good way to traverse the set.

Source code:
Copy codeThe Code is as follows:
Function getLists (){
Var clientContext = new SP. ClientContext ();
Var oWebSite = clientContext. get_web ();
ListCollection = oWebSite. get_lists ();
ClientContext. load (listCollection );
ClientContext.exe cuteQueryAsync (Function. createDelegate (this, this. onGetListsSucceeded), Function. createDelegate (this, this. onGetListsFailed ));
}
Function onGetListsSucceeded (){
Var str = "";
Var listsEnumerator = listCollection. getEnumerator ();
While (listsEnumerator. moveNext ()){
Var objList = listsEnumerator. get_current ();
Str + = "<a href = '" + "http: // localhost" + objList. get_parentWebUrl () + objList. get_defaviewviewurl () + "'>" + objList. get_title () + "</a>" + "<br/> ";
}
Document. getElementById ("lists"). innerHTML = str;
}
Function onGetListsFailed (sender, args ){
Alert ('request failed. '+ args. get_message () +' \ n' + args. get_stackTrace ());
}

CAML query:

Two query methods are provided here, one by DueDate and the other by Title. Of course, the function can be designed to be more conducive to user use, so there will be no excessive rendering in the Demo. Click Search to query data. If you select a date when using the <asp: calendar/> control, the page will be postback, there are at least two solutions in SharePoint:

  1. Add the calendar control to a page and add the following code:

    <Input type = "text" id = "txtDate" name = "txtDate"/>
    <Button value = "lookup" onclick = "document. all ['txtdate']. value =
    Window. showModalDialog ('calendar. aspx '); ">

  2. Use the SharePoint Calendar Control <SharePoint: DateTimeControl runat = server id = "DateTimeControl1" DateOnly = "True"> </SharePoint: DateTimeControl>

After a period of control over the display of the control, if Date is selected, the control for inputting the Date is displayed. If the Title is selected, the control for inputting the Title appears. I would like to use the JQuery method, later, I thought about JQuery's Selector method. The half-Earth and non-foreign use of the following method to combine control:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function changeQueryMethod (){
Var method = $ ("select [id = 'selectquerymethod']"). val ();
If (method = 'title '){
Document. getElementById ('querybytitle'). style. display = "inline ";
Document. getElementById ('querybydate'). style. display = "none ";
}
Else {
Document. getElementById ('querybytitle'). style. display = "none ";
Document. getElementById ('querybydate'). style. display = "inline ";
}
}
</Script>

The details of the CAML query itself is not too much description, if you are interested can see the article (http://www.cnblogs.com/johnsonwong/archive/2011/02/27/1966008.html), this is an article for the 2007 version of CAML, there are a lot of enhancements in 2010, for example, for cross-list Joint query, the corresponding version 2010 will be released later.

Note the following knowledge:

The field query is used in it. Pay attention to calling related APIs;
Operations are performed on several result sets in ClientContext, but Load needs to be called to load different result sets: clientContext. load (fieldCollection); clientContext. Load (listItemCollection );
If the field values to be read need to be displayed in the CAML query XML, otherwise they will not be returned to the result set. This is also due to performance considerations.
Copy codeThe Code is as follows:
Function search (){
Var clientContext = new SP. ClientContext ();
Var oWebSite = clientContext. get_web ();
Var list = oWebSite. get_lists (). getByTitle ("Tasks ");
FieldCollection = list. get_fields ();
Var camlQuery = new SP. CamlQuery ();
CamlQuery. set_viewXml ("<View> <Query> <Where> <Gt>" +
"<FieldRef Name = 'duedate'/>" +
"<Value Type = 'datetime'> 2008-01-1T00: 00: 00Z </Value>" +
"</Gt> </Where> </Query> <ViewFields>" +
"<FieldRef Name = \" Title \ "/> <FieldRef Name = \" Body \ "/>" +
"<FieldRef Name = \" DueDate \ "/>" +
"</ViewFields> </View> ");
ListItemCollection = list. getItems (camlQuery );
ClientContext. load (fieldCollection );
ClientContext. load (listItemCollection );
ClientContext.exe cuteQueryAsync (Function. createDelegate (this, this. onSearchListSucceeded), Function. createDelegate (this, this. onSearchListFailed ));
}
Function onSearchListSucceeded (){
Var str = "";
Var listItemEnumerator = listItemCollection. getEnumerator ();
Var fieldsEnumerator = fieldCollection. getEnumerator ();
While (listItemEnumerator. moveNext ()){
Var oListItem = listItemEnumerator. get_current ();
Str + = "Item" + oListItem. get_id () + ":"
While (fieldsEnumerator. moveNext ()){
Var oField = fieldsEnumerator. get_current ();
Str + = oField. get_staticName () + "<br/> ";
}
Str + = "<br/> ";
}
Document. getElementById ("lists"). innerHTML = str;
}

Function onSearchListFailed (sender, args ){
Alert ('request failed. '+ args. get_message () +' \ n' + args. get_stackTrace ());
}

Operation file:

Unfortunately, files cannot be uploaded in ECMAScript. Although SP. File objects exist, operations are performed on the obtained SP. File objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.