I have Model to represent User. I have created a helper class to return a set of these Users, as List(Of Users).
Here is how I do that
Function getDoctorsList() As List(Of Users)
Dim userCollection As New List(Of Users)
Dim sql = "SELECT * FROM " + _tblName + " WHERE usertype = 'doctor'"
Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
While dr.Read
Dim user As New Users
user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
userCollection.Add(user)
End While
Return userCollection
End Function
I grab them, and send them to view to from the controller like this:
ViewData("LoginUserModel") = New LoginUser
ViewData("doctorList") = usersHelper.getDoctorsList
Now, Model has two properties Id and UserName I would like to use as a value and text respectively.
I tried something like this, but this gives type casting problems. SO I am obviously doing it wrong.
<%= Html.DropDownList("doctors", ViewData("doctorList")) %>
How to pass the List as SelectListItems to the DropDownList?
You could use LINQ to project your
List(Of User)into anIEnumerable(Of SelectListItem):or you could also use the
SelectListconstructor:and inside your view:
but I would rather recommend you using view models instead of
ViewData.