Click here to Skip to main content
13,559,785 members
Rate this:
Please Sign up or sign in to vote.
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)
Posted 16-Jan-13 2:34am
Updated 16-Jan-13 3:10am
Zoltán Zörgő 16-Jan-13 8:47am
You can improve on several points, but let me understand your domain: one location can have several cities? Why?
devdev13 16-Jan-13 9:05am
It's just a test application. I used something like that so that I can create views of type 'Location' model, and can access everything in it. Please feel free to correct it. But at the moment, I just want to improve the code in Controller and View. Thanks for the response.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


Try the following code

public ActionResult Index()
     ViewBag.CitiesDropDown = GetCityList();
     return View();

private List<selectlistitem> GetCityList()
     //Here you can access DB to get your required data. Just make sure the return type
     List<selectlistitem> itemList = new List<selectlistitem>();
     itemList.Add(new SelectListItem { Text = "City1", Value = "1", Selected = true });
     itemList.Add(new SelectListItem { Text = "City2", Value = "2" });
     itemList.Add(new SelectListItem { Text = "City3", Value = "3" });
     return itemList;

and then in your view

@Html.DropDownList("City_Code", ViewBag.CitiesDropDown as List<selectlistitem>, "")</selectlistitem>

Hope this simplifies you :)
devdev13 16-Jan-13 9:15am
Thanks for the Reply. Could you please give me some information about why/when we use SelectListItem class, and why we set the "Selected" property to true ?
Sheikh Muhammad Haris 16-Jan-13 11:04am
Sorry I have copied Selected= true to all the items here, which is not possible in case of DropDownList.

Selected = true is used to show default value in dropdown at Page_Load
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

You have several ways to do this. You don't even need to use ViewBag.
Please look at my recent article: Dynamic tabular input with unobstructive validation in ASP.NET MVC3[^] (:)). It covers this scenario also.
SelectListItem is useful if you generate your element on the fly, Selected has to be set only at one single item if you have dropdown, but as the same class can be used to fill a listbox, and you enable multiselect, than setting multiple this property to true at multiple elements is also viable.
devdev13 16-Jan-13 11:12am
Sure, will do..Thanks..!!
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Create a class DropdownList<t> where T is the entity which contain the property for value and text and method like below

public static class DropDownList<T>
       public static SelectList LoadItems(IList<T> collection, string value, string text)
           return new SelectList(collection, value, text);

Call the method like below.First Argument is the IEnumerable collection of records that you need to populate in the dropdown and remaining arguments are the value field and text field.
ViewData["LoadCities"] = DropDownList<City>.LoadItems(_requestRepository.GetCities(),"Id","City");

Call from the view like below

@Html.DropDownListFor(model => model.Id, (IEnumerable<selectlistitem>)ViewData["LoadCities"], "--Select--", new { @class = "select" })

You can reuse the DropDownList to pulate the dropdown list.Hope this helps

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web04-2016 | 2.8.180527.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

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