VB.Net、MVC3、Razor、EF 4.1 DB First和Linq-填充DDL选项和值



背景-我正试图用数据库中的状态信息填充下拉列表。我希望完整的州名称作为选项,州缩写作为值。示例:

<option value="AL">ALABAMA</option>

当前进度-数据库中已存在完整的状态名称和缩写。我已经成功地用数据库中的完整状态名填充了DDL。这是我用来做这件事的代码(减去我认为无关紧要的东西)。

模型上下文(根据模板生成):

Partial Public Class BrokerCRMEntities
    Public Property States() As DbSet(Of State)
End Class

状态模型(根据模板生成):

Partial Public Class State
    Public Property StateAbbrev As String
    Public Property StateFull As String
End Class

控制器:

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,其中包含完整的状态名称。示例:

<option>ALABAMA</option>

问题-除了像上面所做的那样填充完整的状态名称外,我还想用DB/模型中的状态缩写填充同一DDL中选择选项的值。这是怎么做到的?

谢谢!

我建议您使用视图模型以及强类型视图和DropDownListFor辅助对象。因此,一如既往地从视图模型开始:

Public Class StatesViewModel
    Public Property SelectedState As String
    Public Property States As IEnumerable(Of State)
End Class

那么控制器:

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")
)

相关内容

  • 没有找到相关文章

最新更新