I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me.
Action Method
public class VehicleController : Controller
{
private readonly IService<Vehicle> _service;
public VehicleController(IService<Vehicle> service)
{
_service = service;
}
public JsonResult AutoComplete(string term)
{
var vehicle = _service.GetAll().Select(c => new { Name = c.Name });
return Json(vehicle, JsonRequestBehavior.AllowGet);
}
}
EntityRepository
public class EntityRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
private readonly IEntitiesContext _context;
private readonly IDbSet<TEntity> _dbEntitySet;
private bool _disposed;
public EntityRepository(IEntitiesContext context)
{
_context = context;
_dbEntitySet = _context.Set<TEntity>();
}
public List<TEntity> GetAll()
{
return _dbEntitySet.ToList();
}
}
IRepository
public interface IRepository<TEntity> : IDisposable where TEntity : BaseEntity
{
List<TEntity> GetAll();
}
Service
public class Service<TEntity> : IService<TEntity> where TEntity : BaseEntity
{
public IUnitOfWork UnitOfWork { get; private set; }
private readonly IRepository<TEntity> _repository;
private bool _disposed;
public Service(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
_repository = UnitOfWork.Repository<TEntity>();
}
public List<TEntity> GetAll()
{
return _repository.GetAll();
}
}
IService
public interface IService<TEntity> : IService where TEntity : BaseEntity
{
List<TEntity> GetAll();
}
Action Method is returning a complete list of data but when I apply any filter it won't work and returns no values -- e.g I tried this and it returns null:
var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term)).Select(c => new { Name = c.Name });
termparameter from action to service method?termmatches any result in your DB? Remember this comparison is case-sensitive(so 'm' doesn't match 'M')ToList()method beforeWhere()so further comparison is not the part ofLinqToSql.GetAll()returns aVehicleenumeration, but.GetAll().Where...Select(c=>new { Name... })returns astringenumeration.