通过组织服务中获取实体picklist字段的text和value可以通过RetrieveAttributeRequest实现,但在使用web api的今天该怎么实现,本文即来一探究竟,本篇基于SDK中的Query Metadata using the Web API一节。
首先我们要获取到实体的metadataid,代码如下,这个metadataid后面会用到,我这里用的是account实体
string weburi = WebUri + "EntityDefinitions?$filter=LogicalName eq 'account'"; string result = ""; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(weburi); req.Credentials = new NetworkCredential(username, pwd, domain); req.Method = "Get"; req.Accept = "application/json"; req.ContentType = "application/json; charset=utf-8"; req.Headers.Set("OData-MaxVersion", "4.0"); req.Headers.Set("OData-Version", "4.0"); using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) { StreamReader read = new StreamReader(res.GetResponseStream()); result = read.ReadToEnd(); } JObject jobject = JsonConvert.DeserializeObject<JObject>(result); string id = jobject["value"][0]["MetadataId"].ToString();
string weburi = WebUri + +"EntityDefinitions("+ metadataid + ")/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet,GlobalOptionSet"; ; string result = ""; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(weburi); req.Credentials = new NetworkCredential(username, pwd, domain); req.Method = "Get"; req.Accept = "application/json"; req.ContentType = "application/json; charset=utf-8"; req.Headers.Set("OData-MaxVersion", "4.0"); req.Headers.Set("OData-Version", "4.0"); using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) { StreamReader read = new StreamReader(res.GetResponseStream()); result = read.ReadToEnd(); } JObject jobject = JsonConvert.DeserializeObject<JObject>(result); JArray ja = (JArray)jobject["value"]; string text = ""; if (ja.Count > 0) { for (int i = 0; i < ja.Count; i++) { if (ja[i]["LogicalName"].ToString() == "new_testoption") { if (ja[i]["OptionSet"].ToString() != "") { ja = JsonConvert.DeserializeObject<JArray>(ja[i]["OptionSet"]["Options"].ToString()); for (int j = 0; j < ja.Count; j++) { if (ja[j]["Value"].ToString() == "100000000") { ja = JsonConvert.DeserializeObject<JArray>(ja[j]["Label"]["LocalizedLabels"].ToString()); text = ja[0]["Label"].ToString(); } } } else { ja = JsonConvert.DeserializeObject<JArray>(ja[i]["GlobalOptionSet"]["Options"].ToString()); for (int j = 0; j < ja.Count; j++) { if (ja[j]["Value"].ToString() == "0") { ja = JsonConvert.DeserializeObject<JArray>(ja[j]["Label"]["LocalizedLabels"].ToString()); text = ja[0]["Label"].ToString(); } } } } } }这里的json处理用的是newtonsoft,如果要引用上述代码记得添加 newtonsoft的引用,上述代码是根据picklist的value值去查找对应的text的,反之亦然。