模型
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" />
}
如何在控制器中获取所选的复选框值和文本?
答案 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
将呈现如下所示。
当您选择India
和US
并点击提交按钮时,您将获得如下的POST参数。