Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
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.
C#
//ViewModel

 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 ?
C#
//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.
HTML
//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>
Posted
Updated 16-Jan-13 3:10am
v2
Comments
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.

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

C#
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.
C#
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
 
Share this answer
 
v4
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.
 
Share this answer
 
Comments
devdev13 16-Jan-13 11:12am    
Sure, will do..Thanks..!!
Hi,

Try the following code

C#
[HttpGet]
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
@Html.DropDownList("City_Code", ViewBag.CitiesDropDown as List<selectlistitem>, "")</selectlistitem>



Hope this simplifies you :)
 
Share this answer
 
v3
Comments
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 ?
[no name] 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

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

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900