开发者

Determining which checkboxes are not checked in ASP.NET MVC?

Imagine a page which uses checkboxes to keep track of mailing list subscriptions about pets:

cats-list ( )
dogs-list (*)
birds-list ( )
horses-list (*)

I use ASP.NET MVC's Html.Checkbox extension method in a loop (not shown):

<%= Html.Checkbox("subscriptions[" + i +"]", item.subscribed, item.listName) %>

"i" is the iteration variable in the loop. Using this convention allows my controller action to model bind subscriptions[i] to a List<string> which then contains a list of mailing list names to subscribe to.

How can I keep track of what's not checked? For example, if a user unchecks "dogs-list" to unsubscribe from that list, how can I tell? I'll only get "false" back from the hidden form field.

开发者_Python百科

EDIT: The only solution which comes to mind is for the controller action to unsubscribe from all mailing lists, and then resubscribe to lists contained in the List<string> from the checkboxes. That's not ideal though.


You basically answered it yourself with the edit but something a bit more elegant would be better. I.e. Don't delete them all first, just determin which need to be added, which need to be deleted and which need to just remain.

E.g. (air code)

List<string> selectedSubscriptions; //This is passed in from the form using the model binder
List<string> mailingListsToRemove = GetCurrentMailingLists(); //Looks odd but bear with me
List<string> mailingListsToAdd = new List<string>();

//Loop through all the mailing lists they had selected
foreach (string selectedMailingList in selectedSubscriptions)
{
    //if the mailing list exists in the list to remove, remove it from that list
    //because they obviously don't want it removed
    //Remember that this list also contains their current lists.
    if (mailingListsToRemove.Contains(selectedMailingList))
    {
        mailingListsToRemove.Remove(selectedMailingList);
    }
    else //If it's not in the list to remove then add it
    {
        mailingListsToAdd.Add(selectedMailingList);
    }
}

So at the end of that loop you should have two lists - one containing all the mailing lists that the user wants removed and one containing all the new mailing lists they want to be subscribed to. The mailing lists that they were already subscribed to and still wish to be subscribed to should just be left alone.

HTHs,
Charles

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜