在大量编辑表单页面上,我显示了大约50个具有布尔属性的对象。控制器从编辑页面接收具有所有值的FormCollection。
public void _EditAll(FormCollection c)
{
int i = 0;
if (ModelState.IsValid)
{
var arrId = c.GetValues("channel.ID");
var arrName = c.GetValues("channel.displayedName");
var arrCheckbox = c.GetValues("channel.isActive");
for (i = 0; i < arrId.Count(); i++)
{
Channel chan = db.Channels.Find(Convert.ToInt32(arrId[i]));
chan.displayedName = arrName[i];
chan.isActive = Convert.ToBoolean(arrCheckbox[i]);
db.Entry(chan).State = EntityState.Modified;
}
db.SaveChanges();
}
}现在,对于复选框,MVC在表单上创建隐藏的输入(否则"false“无法回发)。在控制器中,当接收到FormCollection时,这就导致了这样的情况,即我收到了一个数组
因为隐藏复选框具有与可见复选框相同的名称。
有什么好的方法来处理这个问题并得到正确的复选框值呢?
发布于 2013-11-10 17:29:21
用于编辑具有布尔字段的实体数组的示例。
实体:
public class Entity
{
public int Id { get; set; }
public bool State { get; set; }
}主计长:
public ActionResult Index()
{
Entity[] model = new Entity[]
{
new Entity() {Id = 1, State = true},
new Entity() {Id = 2, State = false},
new Entity() {Id = 3, State = true}
};
return View(model);
}
[HttpPost]
public ActionResult Index(Entity[] entities)
{
// here you can see populated model
throw new NotImplementedException();
}查看:
@model Entity[]
@{
using (Html.BeginForm())
{
for (int i = 0; i < Model.Count(); i++ )
{
@Html.Hidden("entities[" + i + "].Id", Model[i].Id)
@Html.CheckBox("entities[" + i + "].State", Model[i].State)
}
<input type="submit"/>
}
}唯一棘手的事情是html元素的命名。
关于绑定数组的更多信息。
发布于 2013-11-10 17:07:16
我正在转换包含复选框值的所有数组:
"false“=> "false",如果前面没有"true”
https://stackoverflow.com/questions/19892045
复制相似问题