Reputation: 2425
There are few tabs and a content panel. End user (EU) will click on a tab and the panel's content changes asynchronously.
eg:
<ul class="products">
<li class="p1">product1</li>
<l1>product2</li>
</ul>
<div class="product-data">
NAME : <span> <product name here> </span>
COLOR : <span> <product color here> </span>
</div>
<script>
(function ($) {
$(".p1").click(function(){
HelloWorld();
});
function HelloWorld() {
$.ajax({
type: "POST",
url: 'http://mysite/Services/myService.asmx/HelloWorld',
data: "pid:" + someId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert("ERR-" + response.d);
}
});
}
})(jQuery);
</script>
Each product is an item in the content tree. When EU clicks on a tab, an ajax call is made, which will get that product's data and bind to the panel.
I'm trying to achieve this functionality using a web service and return JSON to front end:
[WebMethod]
public string HelloWorld(string pid)
{
//get a certain product details and return it as JSON
Sitecore.Data.Items.Item newItem = Sitecore.Context.Item;
if (newItem != null)
return newItem.Name;
else
return "it was null";
}
Of course, the result is "it was null" as I understand this has to be done with Item Service of SSC, but unable to find any suitable/beginner example.
Using sitecore 8 with ASP.NET
Upvotes: 0
Views: 1189
Reputation: 2047
You will want to use Entity Service
instead of Item Service
of Sitecore.Services.Client
. It will let you serve custom models that are specific to the type of data you want to display for each product.
First, you will need to create a class to represent your Product. It needs to implement Sitecore.Services.Core.Model.EntityIdentity
.
Just an FYI if you are using Sitecore SPEAK ensure you define a property named itemId
with that casing, SPEAK requires it.
public class ProductModel : Sitecore.Services.Core.Model.EntityIdentity
{
public string itemId { get; set; }
public string ProductName { get; set; }
...
}
When Developing with Sitecore.Services.Client
you'll want to follow Sitecore best practices. A simple Controller
passing off all the computation to a Repository
for the type of Model. In this case a ProductRepository.
The controller needs to implement EntityService
with the type of Model
.
[ValidateAntiForgeryToken]
[ServicesController]
public class ProductController : EntityService<ProductModel>
{
public ProductController(IRepository<ProductModel> repository)
: base(repository)
{
}
public ProductController()
: this(new SitecoreItemRepository())
{
}
}
This controller exposes the methods of the Repository
Get, GetById, Add, etc.
public class ProductRepository : Sitecore.Services.Core.IRepository<ProductModel>
{
public ProductModel FindById(string id)
{
// code to find by id
}
}
See here for a full example of Entity Service and here
Upvotes: 2