将模型类通过复选框值传递给控制器

时间:2013-12-06 16:47:58

标签: c# asp.net-mvc-4

我的测试类有一个test2类列表作为其成员之一,当选中一个复选框时,我想将每个test2类传递回控制器。

编辑:我从下面的报告选择器更新了模型以测试以匹配我上面的描述。

模型测试

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace ImpactIndicator.Models
{
public enum ComparisonSideBySideValue { School, Entry };

public class test
{
    public List<test2> Schools
    {
        get
        {
            if (HttpContext.Current.Session["ReportChooser_SchoolInfo"] != null)
            {
                List<ReportSchoolInfo> schools=(List<ReportSchoolInfo>)HttpContext.Current.Session["ReportChooser_SchoolInfo"];
                schools.OrderBy(t=>t.DistName).ThenBy(t=>t.SchoolName);
                return schools;
            }
            else
                return null;
        }
        set
        {
            HttpContext.Current.Session["ReportChooser_SchoolInfo"] = value;

        }
    }
}
}

模型test2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ImpactIndicator.Models
{
public class test2
{
    public string SchoolName { get; set; }
    public string DistName { get; set; }
    public int SchoolID { get; set; }
    public int DistID { get; set; }
    public int? SchoolLevelID { get; set; }
}
}

视图

int counter1 = 0;

foreach (var item in ViewBag.ReportSchools)
{
    if (counter1 % 2 == 0)
    {
                    @:<tr>
                }

                <td>

                @{
    bool isSelected = false;
    if (ViewBag.ReportChooser.Schools != null)
    {
        foreach (var selSchoolID in ViewBag.ReportChooser.Schools)
        {
            if (item.ToString() == selSchoolID)
            {
                isSelected = true;
                break;
            }
        }

    }
    if (isSelected)
    {
                        <input type='checkbox' name='Schools' id='Schools' value="@item" class="rptschool" checked="checked" /> @:@item.DistName/@item.SchoolName &nbsp;&nbsp;
                    }
    else
    {
                        <input type='checkbox' name='Schools' id='Schools' value="@item" class="rptschool" /> @:@item.DistName/@item.SchoolName &nbsp;&nbsp;
                    }

                    }

                @*@Html.CheckBox(schoolName, new { @class = "rptschool" }) @item.DistName/@item.SchoolName &nbsp;&nbsp; *@
                </td>

    if (counter1 % 2 == 1 || counter1 == ViewBag.SchoolCount - 1)
    {
                    @:</tr>
                }

    counter1++;
}

1 个答案:

答案 0 :(得分:0)

您的复选框上有相同的名称,以便您可以

Request.Form["Schools"].ToString() 
在您的控制器上

,这将为您提供该列表中所有选中复选框的列表