Creating quick suburbs look up using ASP.NET Core web API and Angular 2 – part 1
In this tutorial I will be building a Australian suburb look up module using ASP.NET Core web API, as the first part I will create the server side. check out the part 2 for client side using Angular 2.
Below is my SuburbsController.cs
public class SuburbsController : BaseController
{
private readonly ISuburbRepository _repository;
public SuburbsController(ISuburbRepository repository)
{
_repository = repository;
}
[HttpGet("")]
public IActionResult Get()
{
var result = _repository.GetAll();
return Ok(Mapper.Map<IEnumerable<SuburbViewModel>>(result));
}
[HttpGet("Search")]
public IActionResult Search(string searchTerm)
{
var result = _repository.GetAll(searchTerm.Trim());
return Ok(Mapper.Map<IEnumerable<SuburbViewModel>>(result));
}
}
This is how SuburbViewModel.cs looks like, yeah simple as it can be
public class SuburbViewModel
{
public int SuburbId { get; set; }
public string Name { get; set; }
public int PostCode { get; set; }
public string State { get; set; }
}
Since this a quick tutorial I will do the SuburbRepository.cs like below, let me know if there is a better way.
public class SuburbRepository : Repository<Suburb>, ISuburbRepository
{
public SuburbRepository(ExchangeMonitorContext context) : base(context) { }
public IQueryable<Suburb> GetAll(string searchTerm)
{
var sql = "SELECT * FROM ExchangeMonitor.Suburb WHERE 1=1";
if (!string.IsNullOrWhiteSpace(searchTerm))
sql += $" AND (Name LIKE '%{searchTerm}%')";
var items = Context.Suburbs.FromSql(sql);
return items;
}
}
