Updating a list of objects in mvc4

后端 未结 1 1196
刺人心
刺人心 2020-12-12 05:52

I have taken an issue that I am having with a asp.net mvc4 applications and simplified it so I can post it here. My basic problem is that I am trying to send a list of items

相关标签:
1条回答
  • 2020-12-12 06:06

    So you have to have some understanding of how HTML forms work as well as how the MVC model binder works.

    Checkboxes only send a value back in the post data if they are checked.

    Next, the model binder in MVC will reconstitute collection/list objects as long as the field naming follows the proper naming convention.

    So your loop For Each item In Model needs to produce items with the correct name.

    Let's change your model slightly.

    Public Class PeopleModel
      Public Property People As List(Of Person)
      Public Property SelectedPeople As List(Of Int64)  ' Assuming Person.ID is Int64
    End Class
    

    Then your change your view's loop like so:

    Dim itemIndex As Int32 = 0
    For Each person As Person In Model.People
      @<input type='checkbox' name='SelectedPeople[@itemIndex]' id='person_@person.ID' value='@person.ID' />
      @<input type='hidden' name='SelectedPeople[@itemIndex]' value='-1' />
      itemIndex += 1
    Next
    

    We place the hidden element in there because it will provide a field value for unchecked items. Otherwise the first unchecked item would break the indices and the model binder would stop.

    Now in your controller's post handler:

    <HttpPost>
    Public Function ActionName(model As PeopleModel) As ActionResult
    
      For Each id As Int64 In model.SelectedPeople
        If 0 < id Then
          ' This is the id of a selected person - do something with it.
        End If
      Next
    
    End Function
    
    0 讨论(0)
提交回复
热议问题