Click here to Skip to main content
13,351,731 members (53,818 online)

ASP.NET MVC - Help needed to Improve the code for mvc's Drop-Down Box?

devdev13 asked:

Open original thread
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" };

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.
    List<TestApp.Models.CityDTO> citiesList = ViewBag.CitiesDropDown;
    var cityItems = new SelectList(citiesList, "CityId", "CityName");
    Cities: @Html.DropDownListFor(x => x.Cities.SingleOrDefault().CityID, @cityItems)
Tags: .NET, ASP.NET, MVC, jQuery


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

Advertise | Privacy |
Web02 | 2.8.180111.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100