I have just started with my project using MVC and Razor. Now I am encountering a problem when it comes to binding data coming from the database to a dropdownlist. Please refer on my codes below:
Specialization Model:
public class SpecializationModel
{
[Display(Name = "SpecializationID")]
public string SpecializationID { get; set; }
[Display(Name = "SpecializationDescription")]
public string SpecializationDescription { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
public int SelectedSpecializationID { get; set; }
}
Controller:
public ActionResult Physicians()
{
SpecializationManager spec = new SpecializationManager();
List<Specialization> SpecializationList = spec.GetAllSpecialization();
var obj = new SpecializationModel();
obj.Items = new[]
{
foreach(var x in SpecializationList)
{
new SelectListItem { Value = x.SpecializationID.ToString(), Text = x.SpecializationDescription };
}
};
return View(obj);
}
I have this manager which contains my LINQ query to extract the data from the database.
I encounter problems on the controller. Wherein the error points on the foreach
syntax saying Invalid expression term foreach
Can anyone please point me to the right direction? Thanks a lot!
EDIT:
I have this code now without errors on the foreach part (thanks to the post below which I combined with what I have above). However, I can't seem to make the last line work. It produces an error about implicit cast:
var items = new List<SelectListItem>();
foreach (var x in SpecializationList)
{
items.Add(new SelectListItem { Value = x.SpecializationID.ToString(), Text = x.SpecializationDescription });
}
obj.Items = items.ToList();
Please do help me. Thanks :)