[英]VB.Net, MVC3, Razor, EF 4.1 DB First, and Linq - Populating DDL Options and Values
背景- 我正在嘗試使用數據庫中的 state 信息填充下拉列表。 我希望將完整的 state 名稱作為選項,並將 state 縮寫作為值。 例子:
<option value="AL">ALABAMA</option>
當前進展- 數據庫中已經存在完整的 state 名稱和縮寫。 我已經成功地用數據庫中的完整 state 名稱填充了 DDL。 這是我用來執行此操作的代碼(減去我認為不相關的內容)。
Model 上下文(從模板生成):
Partial Public Class BrokerCRMEntities
Public Property States() As DbSet(Of State)
End Class
State Model(從模板生成):
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(StateQuery)
ViewBag.State = New SelectList(StateList)
看法:
@ModelType IEnumerable(Of BrokerCRM.BrokerCRMEntities)
@Html.DropDownList("State", "")
此代碼生成一個 DDL,其中包含完整的 state 名稱。 例子:
<option>ALABAMA</option>
問題- 除了像我在上面所做的那樣填充完整的 state 名稱外,我還想使用 DB2 模型中的 Z9ED39E2EA931586B6A985A6942EF57reviation 中的 Z9ED39E2EA931586B6A985A6942EF57reviation. 這是怎么做的?
謝謝!
我建議您使用視圖 model 以及強類型視圖和DropDownListFor
助手。 所以一如既往地從視圖 model 開始:
Public Class StatesViewModel
Public Property SelectedState As String
Public Property States As IEnumerable(Of State)
End Class
然后是 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
最后是視圖:
@ModelType IEnumerable(Of StatesViewModel)
@Html.DropDownListFor(
Function(x) x.SelectedState,
New SelectList(Model.States, "StateAbbrev", "StateFull")
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.