Reputation: 170
I have a view where multiple entitys are displayed which the user may then select or not. All of this works fine, however I fail to receive this data in my controller.
Controller:
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
}
View:
@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" />
}
When I submitt the Page, the request actually hits the Controller, but the Data isnt visbile in the Controller. The content of the request looks as follows: (checked in 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
Upvotes: 1
Views: 163
Reputation: 33305
Model
public class EventOrphans
{
public int ID { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
Note the Checked property
View for loop
@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>
}
Note the for loop insted of foreach to enable model binding and the hidden fields to allow the values to be posted back to the controller
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
Controller post
[HttpPost]
public ActionResult Index(List<EventOrphans> events)
{
//All the selected events are available in events
return View(events);
}
Note the change from a List<string>
to List<EventOrphans>
Upvotes: 1