嗨,我是 MVC 新手,浏览了大量这些帖子,但无法解决我的问题。
我已经使用 html 帮助程序的 dropdownlist 成功填充了我的下拉列表,但是当我提交表单时,所选项目的值没有与模型一起传递到操作结果中。换句话说,当我调试和检查下拉列表的属性值时,它什么都不是。我相信这会导致“ModelState.isValid”也返回 false。
这是我的模型:
Public Class Warranty
Public Property state As DropDownList
Private _States As IEnumerable(Of State)
Public Property States As IEnumerable(Of State)
Get
If _States Is Nothing Then
_States = GetStates()
End If
Return _States
End Get
Set(value As IEnumerable(Of State))
_States = value
End Set
End Property
Public Shared Function GetStates() As List(Of State)
Dim l As New List(Of State)
l.Add(New State With {.Value = "none", .Text = "Selected One"})
l.Add(New State With {.Value = "UT", .Text = "Utah"})
l.Add(New State With {.Value = "NV", .Text = "Nevada"})
Return l
End Function
End Class
这是我的州级:
Public Class State
Public Property Value As String
Public Property Text As String
End Class
这是我的控制器方法:
' GET: /Warranty
Function WarrantyRegistration() As ActionResult
ViewData("Message") = "Warranty Registration Form"
Dim _statesList As New SoleWebSite.Models.Warranty
Return View(_statesList)
End Function
'
'POST: /Warranty
<HttpPost()> _
Function WarrantyRegistration(ByVal warranty As SoleWebSite.Models.Warranty) As ActionResult
If ModelState.IsValid Then
war.state = warranty.state.SelectedItem.Value.ToString()
// warranty.state
db.AddTowarranty_registrations(war)
db.SaveChanges()
db.Dispose()
Return RedirectToAction("WarrantyRegistration")
End If
Return View(warranty)
End Function
这是我的看法:
<td>@Html.DropDownListFor(Function(m) m.state, New SelectList(Model.States, "Value", "Text"))</td>
我不确定我做错了什么。
我想保持所有的强类型,并尽可能避免使用 viewbag 或 viewdata。
任何建议将不胜感激。
提前致谢。