public ActionResult GroceryNames(string startsWith = null, string contains = null, int maxCount = 10) { JsGroceryResults groceryResults = new JsGroceryResults(); var context = new GroceryContext(); List <GroceryReturnValue> groceries = new List <GroceryReturnValue>(); List <Grocery> possibleGroceryNames; if (startsWith != null) { // filter by startsWith possibleGroceryNames = context.Groceries.Include("Category").Where(g => g.Name.StartsWith(startsWith)).ToList(); } else { // get all and post-filter possibleGroceryNames = context.Groceries.Include("Category").ToList(); } contains = (contains != null) ? contains.ToLowerInvariant() : null; foreach (var grocery in possibleGroceryNames) { if (contains == null || grocery.Name.Contains(contains)) { // upper-case each word in name and add to results var groceryName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(grocery.Name); var groceryValue = new GroceryReturnValue() { Name = groceryName, Category = grocery.Category.Name }; groceryValue.ImageUrl = (!string.IsNullOrEmpty(grocery.ImageUrl)) ? grocery.ImageUrl : null; groceries.Add(groceryValue); } if (groceries.Count == maxCount) { break; } } groceryResults.Count = groceries.Count; groceryResults.Groceries = groceries; JsonResult result = new JsonResult(); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; result.Data = groceryResults; return(result); }
public ActionResult GroceryNames(string startsWith = null, string contains = null, int maxCount = 10) { JsGroceryResults groceryResults = new JsGroceryResults(); var context = new GroceryContext(); List<GroceryReturnValue> groceries = new List<GroceryReturnValue>(); List<Grocery> possibleGroceryNames; if (startsWith != null) { // filter by startsWith possibleGroceryNames = context.Groceries.Include("Category").Where(g => g.Name.StartsWith(startsWith)).ToList(); } else { // get all and post-filter possibleGroceryNames = context.Groceries.Include("Category").ToList(); } contains = (contains != null) ? contains.ToLowerInvariant() : null; foreach (var grocery in possibleGroceryNames) { if (contains == null || grocery.Name.Contains(contains)) { // upper-case each word in name and add to results var groceryName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(grocery.Name); var groceryValue = new GroceryReturnValue() { Name = groceryName, Category = grocery.Category.Name }; groceryValue.ImageUrl = (!string.IsNullOrEmpty(grocery.ImageUrl)) ? grocery.ImageUrl : null; groceries.Add(groceryValue); } if (groceries.Count == maxCount) { break; } } groceryResults.Count = groceries.Count; groceryResults.Groceries = groceries; JsonResult result = new JsonResult(); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; result.Data = groceryResults; return result; }