Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC - Help needed to Improve the code for Drop-Down Box?
    primarykey
    data
    text
    <p>I have created the below drop-down to populate a list of cities. </p> <p>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 &lt; Select > instead of HTML helpers. </p> <p>Below are my DTO classes. Please advise if I can make improvements in the controller and the view as well.</p> <pre><code>//ViewModel public class LocationDTO { public IEnumerable&lt;CityDTO&gt; Cities { get; set; } public LocationDTO() { this.Cities = new CityDTO[] { }; } } public class CityDTO { public string CityId { get; set; } public string CityName { get; set; } } </code></pre> <p>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 ?</p> <pre><code>//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&lt;Models.CityDTO&gt; citiesList = new List&lt;Models.CityDTO&gt;(); 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); } </code></pre> <p>Below is my View. I'd also like to know how the Lamdba expression works in this scenario please. </p> <pre><code>//View @{ List&lt;TestApp.Models.CityDTO&gt; citiesList = ViewBag.CitiesDropDown; var cityItems = new SelectList(citiesList, "CityId", "CityName"); } &lt;div&gt; Cities: @Html.DropDownListFor(x =&gt; x.Cities.SingleOrDefault().CityID, @cityItems) &lt;/div&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload