This is my view model class:
public class CustomerEditViewModel
{
[Display(Name = "Customer Number")]
public string CustomerID { get; set; }
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Display(Name = "Customer Country")]
public string Country { get; set; }
}
I need to populate a dropdown with properties of this class, so the property name will be the value and Display.Name
will be text of the dropdown item.
The <select>
HTML would look like this:
<select>
<option value="">--Select--</option>
<option value="CustomerID">Customer Number</option>
<option value="CustomerName">Customer Name</option>
<option value="Country">Customer Country</option>
</select>
EDIT
Based on Taylor wood answer. i created a small sample code. here it is.
Model code
public class MySkills
{
public IEnumerable<SelectListItem> Skills
{
get;
set;
}
}
public class CustomerEditViewModel
{
[Display(Name = "Customer Number")]
public string CustomerID { get; set; }
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Display(Name = "Customer Country")]
public string Country { get; set; }
}
Controller & action code
public class HomeController : Controller
{
public ActionResult Index()
{
var items = from p in typeof(CustomerEditViewModel).GetProperties()
let name = p.GetCustomAttribute<DisplayAttribute>().Name
select new SelectListItem() { Text = name, Value = p.Name };
var ClassData = new MySkills();
var selectList = new List<SelectListItem>();
foreach (var item in items)
{
selectList.Add(new SelectListItem
{
Value = item.Value.ToString(),
Text = item.Text
});
}
ClassData.Skills = selectList;
return View(ClassData);
}
}
View
@model WebTestDropDown.Controllers.MySkills
@{
ViewBag.Title = "Home Page";
}
<br /><br /><br /><br />
<tr>
<td> Populating With Model Data </td>
<td> @Html.DropDownList("ClassData", Model.Skills) </td>
</tr>