嗨,我是MVC的新手,並瀏覽了大量這些帖子,無法解決我的問題。dropdownlist將null值返回給我的控制器操作結果
我已經使用dropdownlistfor html helper成功地填充了我的下拉列表,但是當我提交表單時,所選項目值不會與模型一起傳遞到操作結果中。換句話說,當我調試和檢查值時,下拉列表的屬性是什麼都沒有。我相信這導致「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
這是我的國家A級:
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。
任何建議,將不勝感激。
在此先感謝。
檢查,如果視圖狀態啓用 – 2012-07-10 17:38:44
@Waleed A.K.,ViewState的?在ASP.NET MVC應用程序中?不僅如此,它還沒有啓用,但這樣的事情甚至不存在:-) – 2012-07-10 17:39:16
@Drain Dimitrov,感謝您的更新:-( – 2012-07-10 18:04:17