接收Controller中的复选框列表

时间:2014-08-08 09:43:19

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

我有一个视图,其中显示了多个实体,然后用户可以选择或不选择。所有这一切都运行正常,但我无法在我的控制器中收到这些数据。

控制器:

public class EventOrphans
{
    public int ID { get; set; }

    public string Name { get; set; }

    //...
}

[HttpGet]
public ActionResult FindOrphanedEvents()
{
    //Some Database Logic removed
    List<EventOrphans> list = new List<EventOrphans>();
    return this.View(list);
}

[HttpPost]
public ActionResult FindOrphanedEvents(List<String> events)
{
    //This is where I stuck
}

查看:

 @model List<Musa.Controllers.AdminController.EventOrphans>

 @using (Html.BeginForm())
 {  
 <dl class="dl-horizontal">

    @foreach (Musa.Controllers.AdminController.EventOrphans evnt in Model)
    {
        <dt>
            <input type="checkbox" name="@evnt.ID" id="@evnt.ID" checked="checked"/> 
        </dt>
        <dd>
            @evnt.Name               
        </dd>
    }
    </dl>
    <input type="submit" class="btn btn-primary" value="Abschicken" />
}

当我提交页面时,请求实际上命中了Controller,但数据在Controller中不是可见的。请求的内容如下所示:(在fiddler中检查)

1=on&2=on&3=on&5=on&6=on&7=on&8=on&9=on&10=on&11=on&12=on&13=on&14=on&15=on&16=on&17=on&29=on&41=on&42=on&53=on&65=on&70=on&71=on&72=on&73=on&77=on

1 个答案:

答案 0 :(得分:1)

<强> Working example

<强>模型

public class EventOrphans
{
    public int ID { get; set; }

    public string Name { get; set; }

    public bool Checked { get; set; }

}

请注意Checked属性

查看循环

@for(var i = 0; i < Model.Count; i++)
{

    <dt>
        @Html.HiddenFor(m => Model[i].ID)
        @Html.HiddenFor(m => Model[i].Name)
        @Html.CheckBoxFor(m = Model[i].Checked)
    </dt>
    <dd>
        @Model[i].Name
    </dd>

}

注意foreach的for循环启用模型绑定,隐藏字段允许将值发布回控制器

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

控制器帖子

[HttpPost]
public ActionResult Index(List<EventOrphans> events)
{
    //All the selected events are available in events

    return View(events);
}

请注意从List<string>List<EventOrphans>

的更改