VB.Net, MVC3, Razor, EF 4.1 DB First, and Linq - Populating DDL Options and Values
Background - I'm trying to populate a drop down list with state information from a database. I'd like the full state name to be the option and the state abbreviation to be the value. Example:
<option value="AL">ALABAMA</option>
Current Progress - The full state names and abbreviations already exist in the DB. I've successfully populated the DDL with full state names from the DB. Here's the code I've used to do this (minus stuff I've deemed irrelevant).
Model Context (generated from template):
Partial Public Class BrokerCRMEntities
Public Property States() As DbSet(Of State)
End Class
State Model (generated from template):
Partial Public Class State
Public Property StateAbbrev As String
Public Property StateFull As String
End Class
Controller:
Dim db As BrokerCRMEntities = New BrokerCRMEntities
Dim StateList = New List(Of String)()
Dim StateQuery = From d In db.States
Order By d.StateFull
Select d.StateFull
StateList.AddRange(开发者_JS百科StateQuery)
ViewBag.State = New SelectList(StateList)
View:
@ModelType IEnumerable(Of BrokerCRM.BrokerCRMEntities)
@Html.DropDownList("State", "")
This code produces a DDL which contains full state names. Example:
<option>ALABAMA</option>
Question - In addition to populating full state names like I've done above, I'd also like to populate the value of the select options in the same DDL with the state abbreviations in my DB/model. How is this done?
Thanks!
I would recommend you using a view model along with a strongly typed view and DropDownListFor
helper. So as always start with the view model:
Public Class StatesViewModel
Public Property SelectedState As String
Public Property States As IEnumerable(Of State)
End Class
then the controller:
Public Function Index() As ActionResult
' TODO: use ctor DI of the repository
Dim db = New BrokerCRMEntities()
Dim model = New StatesViewModel() With { _
Key .States = db.States.OrderBy(Function(x) x.StateFull) _
}
Return View(model)
End Function
and finally the view:
@ModelType IEnumerable(Of StatesViewModel)
@Html.DropDownListFor(
Function(x) x.SelectedState,
New SelectList(Model.States, "StateAbbrev", "StateFull")
)
精彩评论