ASP.NET : generate ListBoxItems from values in database
I want to populate a listbox, so I have to define an array of ListBoxItem. The data is stored in a database.
This is my original method:
public IEnumerable<String> GiveStudentsNormalAsString(int lesson, int class)
{
Lesson l = giveLesson(lesson);
Class c = GiveClass(l, class);
return (from s in c.Students
orderby s.Name, s.FirstName
select s.Name);
}
So "Class" contains a List of Students (a navigational property). What I want to do is not returning an IEnumerable of Strings, but an I开发者_如何学编程Enumerable of SelectListItems.
I started already:
public IEnumerable<SelectListItem> GiveStudentsNormalAsString(int lesson, int class)
{
Lesson l = giveLesson(lesson);
Class c = GiveClass(l, class);
return .Select(student => new SelectListItem
{
Text = ...
Value = ...
};
}
But what do I have to write as Text and Value? for example, I want the Student Number act as Value, how can I do that?
Here's my edmx: EDMX1
You just refer to the student
variable when building the SelectListItem
:
public IEnumerable<SelectListItem> GiveStudentsNormalAsString(int lesson, int class)
{
Lesson l = giveLesson(lesson);
Class c = GiveClass(l, class);
return c.Students.Select(student => new SelectListItem
{
Text = student.Name,
Value = student.Number.ToString()
});
}
Of course it can also be written using the LINQ syntax, if you prefer so:
public IEnumerable<SelectListItem> GiveStudentsNormalAsString(int lesson, int class)
{
Lesson l = giveLesson(lesson);
Class c = GiveClass(l, class);
return (from student in c.Students
select new SelectListItem
{
Text = student.Name,
Value = student.Number.ToString()
});
}
精彩评论