I have created the below drop-down to populate a list of cities.
All works fine, but I would like to know the better ways of doing this please. Also, please let me know if it is possible to create the same drop down using < Select > instead of HTML helpers.
Below are my DTO classes. Please advise if I can make improvements in the controller and the view as well.
(I am fairly a beginner, and haven't reached the concepts of using repository patterns yet) Any help would be greatly appreciated - thanks.
public class LocationDTO
{
public IEnumerable<CityDTO> Cities { get; set; }
public LocationDTO()
{
this.Cities = new CityDTO[] { };
}
}
public class CityDTO
{
public string CityId { get; set; }
public string CityName { get; set; }
}
Below is my Controller, and I've used entity framework database first approach to get the data back from database. Could you please address the improvements that needs to be done on my controller ?
Models.LocationDTO Loc = new Models.LocationDTO();
EF.LocationEntities locCtx = new EF.LocationEntities();
public Action Result Index() {
using(locCtx) {
var locResults = (from q in locCtx.usp_GetAllCities()
Select new Models.CityDTO {
CityId = q.Id,
CityName = q.Name });
loc.Cities = locResults.ToList();
}
List<Models.CityDTO> citiesList = new List<Models.CityDTO>();
Models.CityDTO city = new Models.CityDTO() { CityId = "-1", CityName = "Select City" };
citiesList.Add(city);
citiesList.AddRange(Loc.Cities.ToList());
ViewBag.CitiesDropDown = citiesList;
return view(loc);
}
Below is my View. I'd also like to know how the Lamdba expression works in this scenario please.
//View
@{
List<TestApp.Models.CityDTO> citiesList = ViewBag.CitiesDropDown;
var cityItems = new SelectList(citiesList, "CityId", "CityName");
}
<div>
Cities: @Html.DropDownListFor(x => x.Cities.SingleOrDefault().CityID, @cityItems)
</div>