1

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

任何建议将不胜感激。

提前致谢。

4

1 回答 1

1

选定的值属性应该是简单的标量类型,例如Stringor Integer,而不是复杂类型,例如DropDownList. 顺便说一句,DropDownList 类型是一个经典的 WebForms 服务器端控件,它在 ASP.NET MVC 应用程序中完全没有任何关系。您应该完全摆脱对System.Web.UI.WebControlsASP.NET MVC 应用程序中命名空间的任何引用。所以在你Warranty使用一个简单的类型:

Public Property state As String

在您的 POST 操作中,您只需读取值:

<HttpPost()> _
Function WarrantyRegistration(ByVal warranty As SoleWebSite.Models.Warranty) As ActionResult
    If ModelState.IsValid Then
        war.state = warranty.state
        //  warranty.state
        db.AddTowarranty_registrations(war)
        db.SaveChanges()
        db.Dispose()
        Return RedirectToAction("WarrantyRegistration")
    End If
    Return View(warranty)
End Function
于 2012-07-10T17:34:47.003 回答