In our last Web API article we discussed about Web API functions, and if you have not checked itout yet, click here to know about Web API functions. Today, we are going to discuss about Web API actions. Similarly, function actions are also reusable pieces of code and can bound or unbound. There are lists of pre define actions, which can be referred to from here, but we can also create our own custom actions and call them as well. If you are new to actions, please refer to our older article to learn about creating actions.
We are going to discuss AddMemberList action which is a bound action. Bound actions or functions are called by using full name of the action or function including Microsoft.Dynamics.CRM namespace, so we need to use it like the following,
Microsoft.Dynamics.CRM.AddMemberList
AddMemberList action takes one of the following parameter,
Actually for every Web API action there is a corresponding organization request, for example
AddMemberList has corresponding
AddMemberListRequest. If you will check this request you will see it needs three following required properties,
And this request can be implemented using the following server side code,
- AddMemberListRequest request = new AddMemberListRequest()
- {
- ListId=new Guid ("<<GUID of the target list>>"),
- EntityId = new Guid("<<GUID of the member that we want to add>>")
- };
- organizationService.Execute(request);
As you see we need to set basically two properties, listid where we want to add member and the entity id, which we want to add. So back to Web API, to implement this action using Web API, we need to pass these two properties only. We can use the following POST request to implement it:
- function AddMemberToList() {
- var serverURL = Xrm.Page.context.getClientUrl();
- var data = {
- "EntityId": "<<GUID of the member that we want to add>>"
- };
-
- var req = new XMLHttpRequest();
- req.open("POST", serverURL + "/api/data/v8.0/lists(<<GUID of the target list>>)/Microsoft.Dynamics.CRM.AddMemberList", true);
- req.setRequestHeader("Accept", "application/json");
- req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
- req.setRequestHeader("OData-MaxVersion", "4.0");
- req.setRequestHeader("OData-Version", "4.0");
- req.onreadystatechange = function() {
- if (this.readyState == 4 ) {
- req.onreadystatechange = null;
- if (this.status == 200) {
- alert("Member added to Marketing list");
- } else {
- var error = JSON.parse(this.response).error;
- alert(error.message);
- }
- }
- };
- req.send(JSON.stringify(data));
- }
Now we can create a JavaScript web resource and use the above code. We can call AddMemeberToList method on some event. Make sure you are passing member id based on the list member selected while creating marketing list, for example, if you have created marketing list for lead, you need to pass lead id,
In the next article we will discuss how we can call our custom action using Web API, so stay tuned.
Read more articles on CRM: