提交复选框组为Dictionary <int,dictionary <int,=“”bool =“”>&gt;到控制器</int,>

时间:2015-01-05 14:50:49

标签: asp.net-mvc

我想提交一组复选框作为字典词典:

控制器:

[HttpPost]
public ActionResult Page1(Dictionary<int, Dictionary<int, bool>> multiChoiceAnswers)
{
    //...
}

查看,首先尝试:

foreach (var q in questionGroup.Questions)
{
    <h5>@q.Text</h5>
    foreach (var option in q.MultiChoiceOptions)
    {
        <label><input type="checkbox" name="multiChoiceAnswers[@q.Id][@option.Id]" value="true" />@option.Name</label><br />
        <input type="hidden" name="multiChoiceAnswers[@q.Id][@option.Id]" value="false" />        
    }
}

查看,第二次尝试:

var i = 0;
foreach (var q in questionGroup.Questions)
{
    <h5>@q.Text</h5>
    <input type="hidden" name="multiChoiceAnswers[@i].Key" value="@q.Id" />
    var j = 0;
    foreach (var option in q.MultiChoiceOptions)
    {
        <input type="hidden" name="multiChoiceAnswers[@i][@j].Key" value="@option.Id" />
        <label><input type="checkbox" name="multiChoiceAnswers[@i][@j].Value" value="true" />@option.Name</label><br />
        <input type="hidden" name="multiChoiceAnswers[@i][@j].Value" value="false" />
        j++;
    }                
    i++;
}

结果:字典为空。为什么呢?

1 个答案:

答案 0 :(得分:0)

有效!

<强>控制器:

[HttpPost]
public ActionResult Page1(Dictionary<int, Dictionary<int, bool>> multiChoiceAnswers)
{
    //...
}

查看:

var i = 0;
foreach (var q in questionGroup.Questions)
{
    <h5>@q.Text</h5>
    <input type="hidden" name="multiChoiceAnswers[@i].Key" value="@q.Id" />
    var j = 0;
    foreach (var option in q.MultiChoiceOptions)
    {
        <input type="hidden" name="multiChoiceAnswers[@i].Value[@j].Key" value="@option.Id" />
        <label><input type="checkbox" name="multiChoiceAnswers[@i].Value[@j].Value" value="true">@option.Name</label><br />
        <input type="hidden" name="multiChoiceAnswers[@i].Value[@j].Value" value="false" />
        j++;
    }                
    i++;
}