I am working with mvc 5 and entity framework and on the client side I have implemented a select2 that takes an ajax query as data source. The question is that if my code is efficient so that the search is fast even if there are many results in the search, actually I have doubts in the foreach I don't know if there is a more efficient way to do this.
I need to return the data in the following format:
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
],
}
So create the following class:
public class Select2
{
public int id { get; set; }
public string text { get; set; }
}
And with this code I look for the tables that match the search and convert them to the Select2 model.
[HttpGet]
public async Task<ActionResult> GetMesa(string q)
{
try
{
if (String.IsNullOrEmpty(q) || String.IsNullOrWhiteSpace(q))
{
return Json(new { });
}
else
{
List<Mesa> mesas = await db.Mesa.Where(x => x.NombreMesa.ToLower().StartsWith(q.ToLower())).ToListAsync();
List<Select2> items = new List<Select2>();
foreach(var mesa in mesas)
{
Select2 item = new Select2() {
id = mesa.MesaID,
text = mesa.NombreMesa
};
items.Add(item);
}
return Json(new { items = items },JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new {respuesta = "MesasController => GetMesa \n" + e.Message + e.InnerException});
}
}
Am I doing it in the best way? I know I can paginate it but I'll do that later..
You could perform the query and get the object in the same operation
then you no longer need the foreach