SharePoint Client Object Model (i) ECMA script_javascript tips

Source: Internet
Author: User
Tags object model
The so-called client object model is to invoke the back of the WCF service to provide data, in order to reduce the data access data packets using JSON, we can also see that the design of the object model also added a lot to reduce the number of data traffic considerations. There is no new technology, you want to, in the SharePoint2007 can also achieve similar functions, of course, in the use of the convenience of our many


Three types of client-side models are used. NET managed, ECMA scripts, silverlightclient.

This article explains how to use. NET managed code to access the SharePoint object model.

A few points to note by the ECMAScript Client om

    • ECMAScript can only be used within a SharePoint site and cannot use ECMAScript to access SharePoint site resources in other asp.net sites, nor can access resources across SharePoint sites;
    • jquery and ECMAScript are not used in conflict;
    • To update content securely, add <sharepoint:formdigest runat= "Server" to the screen using ECMAScript/>
    • In the code that you'll see later, in order to reduce the amount of data that is loaded, you can specify what needs to be loaded, such as client. Context.load (This.web, ' Title ', ' Id ', ' Created '), where the attribute value name uses the same system as the CAML, is sensitive to the case;
    • To ensure that your code execution is invoked after the sp.js is loaded, you can use executeordelayuntilscriptloaded (myjsfunction, "Sp.js").

Let's look at a simple match between the SharePoint Om and the client om:

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

Look at the final effect, the following figure is the initial planning function, the main design list of the creation, query and management, but also involved in the upload file case, in the follow-up if there are important will gradually add in.

The links inside will call the UI JavaScript interface to create a SharePoint2010-style pop-up window, and the pop-up window's back page is in the Sitepage document library, and note that this applies only to open pages that are webpart page, If it is not open, it will be reported as an error: "The Ribbon Tab with ID:" Ribbon.read "has not been made to this page or available to not does".

(Note that this page will not be used after this, stay here only to explain ribbon)

To create a list:

First, through designer, add the following two script links:

<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 (which is followed by) are similar, but there are several points to note:

    1. Server-side URLs cannot be used in clientcontext;
    2. does not support LINQ;
    3. Essentially, the ECMAScript OM is asynchronous.

The code is very easy to understand, there is a fun thing SP.UI.Notify.addNotification, through this class can be called in the screen to display a hint message, very SharePoint.

The results of the demo are as follows:

After entering the name of the list in the text box, click the "Create List" button, and then the list will be prompted "list test1 created" in the upper right corner, in this case the annoucement is used as the list type.

The source code is as follows:

Copy Code code 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.executequeryasync (Function.createdelegate (this, this.onquerysucceeded), Function.createDelegate ( This, this.onqueryfailed));
}
function onquerysucceeded () {
Remove the ' creating ' event notification
if (MessageID!= null)
{
Sp. Ui. Notify.removenotification (MessageID);
}
Add ' created ' notification as non sticky
MessageID = SP. Ui. Notify.addnotification ("List <b>" + olist.get_title () + "</b> created ...", false, "", null);
}

function onqueryfailed (sender, args) {
Remove the ' creating ' event notification
if (MessageID!= null)
{
Sp. Ui. Notify.removenotification (MessageID);
}
Shown in case an error on the JS OM call
MessageID = SP. Ui. Notify.addnotification ("Operation was cancelled ...", false, "", null);
}

</script>

Get all lists:

Similarly, first look at the effect, click the "Get all List" button, will be the current site all the lists are read out and set the response hyperlink properties, click the "Hide List" button will be hidden (in fact, is a div)

The code is very straightforward, stating only one point, GetEnumerator (), and the use of JavaScript functions such as MOVENEXST () and get_current () provide a good way to traverse the collection.

Source:

Copy Code code as follows:

function getlists () {
var clientcontext = new SP. ClientContext ();
var owebsite = Clientcontext.get_web ();
Listcollection = Owebsite.get_lists ();
Clientcontext.load (listcollection);
Clientcontext.executequeryasync (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_defaultviewurl () + "' >" + 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:

This provides two ways to query, a press DueDate, a press title, of course, the function can be designed more conducive to user use, the demo will not do too much rendering. Click Search to be able to query the data, there is a small discovery, if the use of <asp:calendar/> control when choosing a good date will cause page postback,sharepoint inside at least two solutions:

    1. Put the calendar control on a separate page, and then 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>

Do a section of control display, select Date to enter the control of the date, select the title will appear to enter the title of the control, would like to use jquery method, and then did not think of the selector of jquery, half of the Earth in combination with the following methods of control:

Copy Code code 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 about the CAML query are not too much explained, if you are interested can see the humble text (http://www.cnblogs.com/johnsonwong/archive/2011/02/27/1966008.html), This is a 2007 version of the CAML, in 2010 has a lot of enhancements, such as cross-list joint query, and then release the corresponding 2010 version.

The knowledge to be noted is:

It uses the query to field, pay attention to the call of relevant API;
There are several result sets operating inside the ClientContext, but you need to invoke load to load different result sets: Clientcontext.load (fieldcollection); Clientcontext.load ( ListItemCollection);
If a field value that needs to be read needs to be shown in the CAML query XML, it is not returned to the result set, which is also due to performance considerations
Copy Code code 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.executequeryasync (this, this.onsearchlistsucceeded), function.createdelegate 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 in the ECMAScript can not upload files, although there are sp.file objects, but more is to get back Sp.file objects to operate.

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.