Keith
Keith

Reputation: 4147

how to query in sitecore

I'm trying to query a certain field in Sitecore while using an Ajax script. The script works if its hard coded with the value :

public void ProcessRequest(HttpContext context)
{
    JOBject j = new JObject(
    new JProperty("test", 10),
    new JProperty("test1", 20)
    );

    context.Response.ContentType = "application/json";
    context.Response.Write(j.ToString(Formatting.None));

}

but what I'm trying to do is find a specific value when there is an input. So the query would search a certain templateid, then when it finds that template it searches a specific field, lets say "Book", and if that field matches the value that was inputted by the user, on the same item, it will display the "Book Number" field which is on the same item that was created in Sitecore.

            try {
                $.ajax({
                  type:"POST",
                  url:"/Test/Test.ajax.ashx",
                  data: {"field":$('#input').val()},
                  cache:false,
                  dataType:'json',
                  success: function(data, status, xhr) {
                    if (data.test== '' || data.test1== '') alert('nothing found');
                    else {
                      $('#test').html(data.test);
                      $('#test1').html(data.test1);
                    }
                  }
                });
            }catch (e) {
                alert(e.message);
            }

Upvotes: 0

Views: 1023

Answers (1)

Chris Auer
Chris Auer

Reputation: 1445

Using the Lucene search context you could use code like this. This would find all items that are based on the given template Id.

using (var context = ContentSearchManager.GetIndex(Search.MasterIndex).CreateSearchContext())
        {
            IQueryable<SearchResultItem> query = context.GetQueryable<SearchResultItem>();
            var computedLanguage = Sitecore.Context.Language.CultureInfo.Name.Replace("-", String.Empty);

            SearchResults<SearchResultItem> results = null;
            query = query.Where(x => x.TemplateId == new ID("{659B67C6-4810-4A22-B9E8-9463005113D6}"));

            results = query.GetResults();
}

You could further refine it by adding a filter on the path.

query = query.Where(x => x.TemplateId == new ID("{659B67C6-4810-4A22-B9E8-9463005113D6}"))
                .Where(x => x.Path.Contains("/Sitecore/Content"));

There are several filters you can use with the Linq object.

Upvotes: 0

Related Questions