Create and call HttpHandler in Sharepointrequirement:
1. Create a HttpHandler, and reture JSON data when call the HttpHandler in client.
2. Create a list named "Products", including a column named "Featuredproduct" which of type is Boolean and the column name D "ProductCategory" which of type is metadata
3. In server, return the JSON and the value of the field named "Featuredproduct" is Yes.
4. In client, get the JSON data with the URL
This is the steps:1. Create SharePoint Project and HttpHandler class
according the Steps
2. Here are the code to create HttpHandler class in VS (using System.Web.Extentions) and then deploy.
Using system;using microsoft.sharepoint;using microsoft.sharepoint.webcontrols;using System.Web;using System.web.script.serialization;using microsoft.sharepoint.taxonomy;using System.collections.generic;namespace testashx{public partial class Test:ihttphandler {public bool IsReusable {get {return True }}//http://weburl/_layouts/15/handler/test.ashx?featuredproduct=1 public void ProcessRequest (HttpCo ntext context) {JavaScriptSerializer Jsonserializer = new JavaScriptSerializer (); Context. Response.ContentType = "Application/json"; int featured = Int. Parse (context. Request.QueryString.Get ("featuredproduct")); list<product> Jsonresult = new list<product> (); String Caml = String. Empty; try {SPContext currentcontext = spcontext.current; SPWeb web = SPContext.Current.Web; SPList List = Web. Lists["Products"]; CAML = "<Where>" + "<Eq>" + "<fieldref name= ' Featur Edproduct '/> "+" <value type= ' Boolean ' > "+ featured +" </Value> "+ "</Eq>" + "</Where>"; SPQuery query = new SPQuery (); Query. Query = Caml; Query. ViewFields = "<viewfields><fieldref name= ' productcategory '/><fieldref name= ' Size '/></ Viewfields> "; SPListItemCollection items = list. GetItems (query); foreach (SPListItem item in items) {Product Product = new Product (); if (item["ProductCategory"] as taxonomyfieldvaluecollection! = null) {Taxonom Yfieldvaluecollection taxonomyfieldvaluecollection = item["ProductCategory"] as taxonomyfieldvaluecollection; if (Taxonomyfieldvaluecollection.count > 0) {product. ProductCategory = taxonomyfieldvaluecollection[0]. Label; }} product. Size = item["Size"]. ToString (); Jsonresult.add (product); }} catch (Exception ex) {context. Response.Write (ex. Message); } context. Response.Write (Jsonserializer.serialize (Jsonresult)); }} class Product {public string ProductCategory {get; set;} public string Size {get; set;} }}
3. In client, this code for call service
$.ajax ({ URL: "Http://webUrl/_layouts/15/handler/Test.ashx?Featuredproduct=0 ", type:" Get ", DataType:" JSON ", success:function (data) { var html =" "; $.each (data, function (index, key) { html + = "<div>" + key. ProductCategory + "</div>"; HTML + = "<div>" + key. Size + "</div>"; }); $ ("#myDiv"). Append (HTML); } });
Note: "Featuredproduct=0" is Variable
Create and call HttpHandler in SharePoint