Reputation: 942
I'm trying to populate a dropdown box with values from a database tables using EF Firstly I'm not sure about the return values here Description is a string so I',m returning a List but this does not work.. Secondly not how the return values can be used to populate the dropdown in my razor page view any guidance appreciated In webforms it was just a databind to the control this seems rather complicated
public List<string> getEstablishments()
{
var db = new mydbContext();
result=db.TblEstablishment.Select(x => new { x.Description }).ToList();
db.Dispose();
return result;
}
Upvotes: 0
Views: 49
Reputation: 497
Change your select statement to Select(x => x.Description).ToList()
. The way it is now you are creating an anonymous object and returning that instead of a string. For binding the establishment in a dropdown you can do the below:
public class EstablishmentOptionView
{
public int EstablishmentId { get; set;}
public string Description { get; set;}
}
public List<EstablishmentOptionView> getEstablishments()
{
var db = new mydbContext();
result=db.TblEstablishment.Select(x => new EstablishmentOptionView {EstablishmentId = x.Id, Description = x.Description }).ToList();
db.Dispose();
return result;
}
//somewhere else
SomeDropDownList.DataValueField = "EstablishmentId";
SomeDropDownList.DataTextField = "Description";
SomeDropDownList.DataSource = getEstablishments();
SomeDropDownList.DataBind();
Upvotes: 1
Reputation: 386
In Razor:
//in your code, myEstablishments would be passed in somehow
List<string> _myEstablishments = new List<string> {"one", "two"};
@Html.DropDownList(name: "myDropDownList", selectList: _myEstablishments.Select(s => new SelectListItem() { Text = s, Value = s });
Upvotes: 1