Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 确定ASP.NET MVC中未选中哪些复选框?_Asp.net Mvc - Fatal编程技术网

Asp.net mvc 确定ASP.NET MVC中未选中哪些复选框?

Asp.net mvc 确定ASP.NET MVC中未选中哪些复选框?,asp.net-mvc,Asp.net Mvc,想象一下,有一个页面使用复选框跟踪关于宠物的邮件列表订阅: cats-list ( ) dogs-list (*) birds-list ( ) horses-list (*) 我在循环中使用ASP.NET MVC的Html.Checkbox扩展方法(未显示): “i”是循环中的迭代变量。使用此约定允许我的控制器操作将订阅[i]模型绑定到列表,该列表包含要订阅的邮件列表名称列表 我如何跟踪未检查的内容?例如,如果用户取消选中“dogs list”以从该列表中取消订阅,我如何判断?我只会从隐

想象一下,有一个页面使用复选框跟踪关于宠物的邮件列表订阅:

cats-list ( )
dogs-list (*)
birds-list ( )
horses-list (*)
我在循环中使用ASP.NET MVC的Html.Checkbox扩展方法(未显示):


“i”是循环中的迭代变量。使用此约定允许我的控制器操作将
订阅[i]
模型绑定到
列表
,该列表包含要订阅的邮件列表名称列表

我如何跟踪未检查的内容?例如,如果用户取消选中“dogs list”以从该列表中取消订阅,我如何判断?我只会从隐藏表单字段返回“false”


编辑:想到的唯一解决方案是控制器操作从所有邮件列表中取消订阅,然后从复选框中重新订阅
列表中包含的列表。但这并不理想。

基本上你自己用编辑来回答,但是稍微优雅一点会更好。也就是说,不要先将它们全部删除,只需确定哪些需要添加,哪些需要删除,哪些需要保留即可

例如(航空代码)

列出所选订阅//这是使用模型活页夹从表单传入的
List mailingListsToRemove=GetCurrentMailingLists()//看起来很奇怪,但请容忍我
List mailingListsToAdd=新列表();
//循环浏览他们选择的所有邮件列表
foreach(selectedSubscriptions中的字符串selectedMailingList)
{
//如果要删除的列表中存在邮件列表,请将其从该列表中删除
//因为他们显然不想把它拿走
//请记住,此列表还包含其当前列表。
if(mailingListsToRemove.Contains(selectedMailingList))
{
mailingListsToRemove.Remove(selectedMailingList);
}
else//如果它不在要删除的列表中,则添加它
{
MailingListToAdd.Add(selectedMailingList);
}
}
因此,在循环结束时,您应该有两个列表-一个包含用户希望删除的所有邮件列表,另一个包含用户希望订阅的所有新邮件列表。他们已经订阅并且仍然希望订阅的邮件列表应该被忽略

HTHs,

查尔斯

我没想到会这样接近它。非常聪明!谢谢。这是另一个简短的评论,再次感谢你。这是我在StackOverflow上收到的最好的代码片段。噢,见鬼,你让我脸红了!很高兴听到这有帮助:-)
<%= Html.Checkbox("subscriptions[" + i +"]", item.subscribed, item.listName) %>
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);
    }
}