I am trying to create a dropdown list to display all the value in a custom collection class
such as
public class MyCustomClassCollection
{
public List<MyCustomClass> {get;set;}
}
I want it to show the Description:string of each MyCustomClass
I tried
<%: Html.DropDownList "Description", MyCustomClass %>
Resharper suggests that I cast MyCustomClass to IEnemerable
but the server returns an unable to cast error.
Any Idea how I can create this DropDownList?
__Modification___
public class ViewModel
{
public Detail detail { get; set; }
}
public class Detail //Inherited from webservce
{
public CustomClassCollection {get;set;}
.... Other Properties, a.k.a Custom Classes
}
public class CustomClassCollection
{
public List<CustomClass> {get;set;}
}
public class CustomClass {
public int Id {get;set;}
public string Description{get;set;}
... other properties
}
public ActionResult Index(int? id, DateTime? date)
{
if (id.Equals(null))
id = ######### ;
if (date.Equals(null))
date = DateTime.Today;
var vm = new ViewModel
{
Detail = _repository.Detail((int)id,(DateTime)date)
};
return View(vm);
}
The second argument of the
DropDownListhelper must be anIEnumerable<SelectListItem>or aSelectListwhich implements this interface for that matter. So in your controller action organize in such a way that you convert your custom collection into anIEnumerable<SelectListItem>. As always you could start by writing a view model:and then have your controller action query the custom list and populate the view model which will be passed to the view:
and finally in your strongly typed view:
UPDATE:
After posting your updated models (which by the way are still incomplete and impossible to compile as you haven’t provided any property names), here’s an example:
and in the view:
What you have to understand in order to define a dropdown list in ASP.NET MVC ius that you need 2 things:
SelectedIdin my example)Model.Detail.MyCollection.CustomClassin the example)