嗨,我是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