获取控制器中的复选框值和文本

时间:2015-07-07 05:42:20

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

模型

public class AllControls
{
    public List<Group> getChkItems { get; set; }
    public bool chk { get; set; }
}

public class Group
{
    public int ID { get; set; }
    public string Name { get; set; }
}

控制器:

[HttpGet]
public ActionResult Index()
{       
    List<Group> li = new List<Group>()
    {
        new Group() { ID = 1, Name = "C#" },
        new Group() { ID = 1, Name = "Asp.NET" },
        new Group() { ID = 1, Name = "SQL" }
    };

    AllControls model = new AllControls();
    model.getChkItems = li;
    return View(model);
}

[HttpPost]
public ActionResult Index(AllControls e)
{
    return View(e);
}

查看:

@using (Html.BeginForm())
{
    foreach (var x in @Model.getChkItems)
    {    
        @Html.CheckBoxFor(m => m.chk, new { value = @x.ID }) @x.Name
        <br />
    }
    <input type="submit" value="Submit" id="btn" />    
}

如何在控制器中获取所选的复选框值和文本?

1 个答案:

答案 0 :(得分:6)

这是我的解决方案。让你的模型如下所示。

public class CheckboxModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

public class MainModel
{
    public List<CheckboxModel> CheckBoxes { get; set; }
}

让您的Controller GET操作如下所示。

public ActionResult GetDatas()
{
    MainModel model = new MainModel();
    var list = new List<CheckboxModel>
    {
         new CheckboxModel{Id = 1, Name = "India", Checked = false},
         new CheckboxModel{Id = 2, Name = "US", Checked = false},
         new CheckboxModel{Id = 3, Name = "UK", Checked = false}

    };
    model.CheckBoxes = list;
    return View(model);
}

POST行动如下所示。

[HttpPost]
public ActionResult PostDatas(MainModel model)
{
    return View(model);
}

View应如下所示。

@model WebApplication1.Controllers.MainModel
@using (Html.BeginForm("PostDatas","Home"))
{
    for (var i = 0; i < Model.CheckBoxes.Count; i++)
    {
        <table>
            <tr>
                <td>
                    @Html.HiddenFor(m => Model.CheckBoxes[i].Id)
                    @Html.HiddenFor(m => Model.CheckBoxes[i].Name)
                    @Html.CheckBoxFor(m => Model.CheckBoxes[i].Checked)
                </td>
                <td>
                    @Html.DisplayFor(m => Model.CheckBoxes[i].Name)                    
                </td>
            </tr>
        </table>

    }
    <input id="submit" type="submit" value="submit" />
}

View将呈现如下所示。

enter image description here

当您选择IndiaUS并点击提交按钮时,您将获得如下的POST参数。

enter image description here