2012-07-10 119 views
1

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

任何建議,將不勝感激。

在此先感謝。

+0

檢查,如果視圖狀態啓用 – 2012-07-10 17:38:44

+1

@Waleed A.K.,ViewState的?在ASP.NET MVC應用程序中?不僅如此,它還沒有啓用,但這樣的事情甚至不存在:-) – 2012-07-10 17:39:16

+0

@Drain Dimitrov,感謝您的更新:-( – 2012-07-10 18:04:17

回答

1

選定的值屬性應該是簡單的標量類型,例如StringInteger,而不是複雜類型,例如DropDownList。順便說一句,DropDownList類型是一個經典的WebForms服務器端控件,它在ASP.NET MVC應用程序中完全無關。您應該擺脫ASP.NET MVC應用程序中對System.Web.UI.WebControls命名空間的任何引用。因此,在您Warranty使用簡單類型:

Public Property state As String 

,並在您的文章的行動,你只是讀取值:

<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 
+0

這正是問題所在,感謝您的快速響應。 – dherrin79 2012-07-10 17:47:39

相關問題