0

I have the following:

public void ProcessRequest(HttpContext context)
{
    string query = context.Request.QueryString["term"];
    System.Web.Script.Serialization.JavaScriptSerializer JsonSerializer =
        new System.Web.Script.Serialization.JavaScriptSerializer();

    List<Category> Categs = Category.getAll();
    var result = from c in Categs where Categs.Contains(c.Name) select c;
    context.Response.ContentType = "application/json";
    context.Response.Write(JsonSerializer.Serialize(result));
}

Trying to return a list of [ { label: "Choice1", value: "value1" }, ... ] for jQuery UI autocomplete. I have Categories which have ID and Name properties and I want to filter the List based on the "term" in the querystring and Name property. How should i do that?

Thanks in advance.

1
  • 1
    FWIW, .NET naming conventions say that JsonSerializer should be jsonSerializer, Categs should be categs, and getAll() should be GetAll(). Also you could avoid typing out System.Web.Script.Serialization.JavaScriptSerializer twice by replacing the first occurance with var. Commented Jul 8, 2012 at 17:02

2 Answers 2

2

If your end goal is making that list of [ { label: "Choice1", value: "value1" }, ... ] and have it sorted by name, then this should work:

result
  .OrderBy(x => x.Name)
  .Select(x => new { label: x.Name, value: x.Id }); // create an anonymous type

Edit: Your current query:

var result = from c in Categs where Categs.Contains(c.Name) select c;

Looks wrong. I think that query is the same as just selecting all Categs. If you want to query based on the term they sent, replace c.Name with query in that linq expression:

var result = from c in Categs where Categs.Contains(query) select c;
Sign up to request clarification or add additional context in comments.

Comments

0
string upperTerm = term.ToUpper();

var result = Category.getAll()
  .Where(c => c.Name.ToUpper().Contains(upperTerm))
  .Select(c => new { label = c.Name, value = c.Id });

Then JSON serialize result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.