Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: ASP.NET .NET MVC jQuery
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.
    //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 ?
    //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>
Posted 16-Jan-13 2:34am
Edited 16-Jan-13 3:10am
v2
Comments
Zoltán Zörgő at 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 at 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
good
Please Sign up or sign in to vote.

Solution 1

Hi,
 
Try the following code
 
[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.DropDownList("City_Code", ViewBag.CitiesDropDown as List<selectlistitem>, "")</selectlistitem>

 
Hope this simplifies you Smile | :)
  Permalink  
v3
Comments
devdev13 at 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 at 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
good
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[^] (Smile | :) ). 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.
  Permalink  
Comments
devdev13 at 16-Jan-13 11:12am
   
Sure, will do..Thanks..!!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Create a class DropdownList 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
  Permalink  
v4

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

  Print Answers RSS
0 OriginalGriff 383
1 Richard Deeming 180
2 Sergey Alexandrovich Kryukov 171
3 Yogesh Kumar Tyagi 165
4 ChauhanAjay 156
0 Sergey Alexandrovich Kryukov 6,252
1 OriginalGriff 5,498
2 CPallini 2,473
3 Richard MacCutchan 1,627
4 Abhinav S 1,530


Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 17 Jan 2013
Copyright © CodeProject, 1999-2014
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