【问题标题】:Getting Checkbox Value and Text in Controller在控制器中获取复选框值和文本
【发布时间】:2015-07-07 05:42:20
【问题描述】:

型号

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" />    
}

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

【问题讨论】:

  • 你真的不需要Post的值,你只需要ID,如果你还需要文本,你应该把它放在hidden hield (Html.Hidden helper)。我想你在Post 上的模型绑定仍然存在问题,here 是一个很好的工作示例,如何避免绑定问题。

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


【解决方案1】:

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

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 Action 如下图所示。

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 将呈现如下所示。

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

【讨论】:

  • 非常感谢。但是我们真的需要隐藏领域吗?
  • 传递NameID,是的,我们需要它们。
  • 这里我们将数据从控制器传递到列表类型的视图。同类型中如何使用Class作为模型?
  • 更新了我的答案,请查收。
  • 非常感谢..你是天才!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多