如何在编辑页面 MVC 中设置下拉列表选定值

how to Set dropdownlist selected value in Edit page MVC

如何在编辑页面设置DropdownList选中项?。 我应该在 DropdownList 中写什么代码而不是 "Nothing"

这是控制器:

' GET: MachinInfo/Edit/5
Function MachinInfoEdit(ByVal id As Integer?) As ActionResult
    If IsNothing(id) Then
        Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
    End If
    Dim machinInfo As MachinInfo = db.MachinInfo.Find(id)
    If IsNothing(machinInfo) Then
        Return HttpNotFound()
    End If
    ViewBag.BrandID = New SelectList(db.Brand, "Id", "BrandName")

    Return View(machinInfo)
End Function

' POST: MachinInfo/Edit/5
<HttpPost()>
<ValidateAntiForgeryToken()>
Function MachinInfoEdit(<Bind(Include:="Id,PelakStateID,MachinStateID,OrgCode,MachineID,BrandID,MachintypeID,NPlate,NPlateL,NPlateM,NPlateR,CardSerial,VIN,Myear,Color,GearTypeID,MCost,Mcamp,Description,LogI,LogE")> ByVal machinInfo As MachinInfo) As ActionResult
    If ModelState.IsValid Then

        db.Entry(machinInfo).State = EntityState.Modified
        db.SaveChanges()
        Return RedirectToAction("Index")
    End If
    ViewBag.BrandID = New SelectList(db.Brand, "Id", "BrandName")

    Return View(machinInfo)
End Function

和我的编辑视图:

<div class="form-group col-md-6">
    @Html.LabelFor(Function(model) model.BrandID, htmlAttributes:=New With {.class = "control-label col-md-2"})
    <div class="col-md-10">
        @Html.DropDownList("BrandID", Nothing, "-select-", htmlAttributes:=New With {.class = "form-control"})
        @Html.ValidationMessageFor(Function(model) model.BrandID, "", New With {.class = "text-danger"})
    </div>
 </div>

您可以使用 SelectList overload with 4 parameters 并将选定的值作为最后一个参数传递:

ViewBag.BrandID = New SelectList(db.Brand, "Id", "BrandName", id.ToString())
ViewBag.DefaultBrand = id.ToString()

然后使用 DirectCastTryCast:

将 ViewBag 内容传递到 DropDownList 帮助程序
@Html.DropDownList("BrandID", TryCast(ViewBag.BrandID, SelectList), ViewBag.DefaultBrand, htmlAttributes := New With { .class = "form-control"})

旁注:

最好创建一个具有 SelectListIEnumerable(Of SelectListItem) 类型的视图模型 属性 -

Public Class ViewModel
    ' other properties

    Public Property SelectedBrandID As Integer
    Public Property BrandList As IEnumerable(Of SelectListItem)
End Class

然后在控制器操作中填充它:

Dim model As New ViewModel
model.BrandList = db.Brand.[Select](Function(x) New SelectListItem() With {
                          .Text = x.Id, 
                          .Value = x.BrandName,
                          .Selected = If(x.Id = id, True, False) }))

Return View(model)

最后使用 DropDownListFor 助手来显示选项列表:

@Html.DropDownListFor(Function(model) model.BrandID, Model.BrandList, Nothing, htmlAttributes := New With { .class = "form-control"})

相关问题:

MVC.NET in VB - Select List to Html.Dropdownlist