views:

111

answers:

1

I've got a list view in my MVC app that shows a check box next to each entry:

<% For Each item In Model%>
    <%=Html.CheckBox("Selected", item.select_flag, New With {.onclick = "this.form.submit();"})%>
    <%=Html.Hidden("ID", item.id)%>
    <%=item.name%>
    <br/>
<% Next%>

As you can tell from the onclick, I'm submitting the form each time a user clicks a check box. In the controller, my post action looks like this:

<AcceptVerbs(HttpVerbs.Post)> _
Function List(ByVal Selected() As Boolean, ByVal ID() As String) As ActionResult

    For i = 0 To ID.Count - 1
        If Selected(i) Then
            [use ID(i) to update a database row]
        End If
    Next

    Return View(GetTheListOfNamesAndIds())

End Function

So I get an array of Selected values and ID's after each checkbox click. I assumed they would correspond, but I'm finding the two arrays to be out of sync for some reason. It's also a lot of overkill to process the whole list every time a checkbox is clicked, so I'd like to revisit this whole setup.

What's the best way to set this up so that clicking a checkbox will update a specific database row? Can it be done without reloading the list each time?

+2  A: 

Consider wrapping each "row" in it's own AjaxForm or using jQuery to do the update via AJAX, then passing the data required for the action via the route values (or form values) in the AJAX get/post. The AjaxForm will want to update some DOM element with new content, but you could get around this by having it update an error message (with nothing if there is success) rather than the actual row and doing any local changes via javascript. With jQuery AJAX you have a lot more options of how you want to handle it but you may have to implement more code on the client side.

tvanfosson