I am trying to pass an IEnumerable
to my controller so that I can loop through each row, make some modifications and add it the database. The problem is that the IEnumerable
is Null
when it is passed back to the controller.
I have read that I need to change my list to IList
and use For instead of ForEach - which I understand..., however, now my IEnumerable
needs to be passed to the View as a IList
and I'm not sure how to do this.
So, I have a couple of questions.
- Is
IList
the only way to go, can I not pass the model to the controller as anIEnumerable
? - If I have to go with
IList
, how do I change my currentAsEnumerable
code to send it to the View asIList
?
Here is the code before any changes to make it IList
were made:
Get controller method:
public ActionResult Register_step6()
{
var wp = cg.GetUserWorkPoint();
var model = (from p in db.WorkPointRoles
where p.WorkPoint == wp
select p).AsEnumerable()
.Select(r => new RegisterEmployee_Step6Model()
{
Role = r.Role,
isSelected = false,
RoleDescription = cg.GetRoleDescription(r.Role),
IconLocation = cg.GetRoleIconLocation(r.Role)
});
return View(model);
}
Post controller method:
[HttpPost]
public ActionResult Register_step6(IEnumerable<RegisterEmployee_Step6Model> model)
{
foreach (var i in model)
{
//code in here to update db
}
db.SaveChanges();
}
return RedirectToAction("Index");
}
}
View:
@model IEnumerable<core_point.Models.RegisterEmployee_Step6Model>
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<h2>Select the roles that you have been employed to do, by clicking the check-box...</h2>
<table class="table">
@foreach (var item in Model)
{
<tr class="h3">
<td class="vert-align">
<img src="@item.IconLocation" height="80" width="80" />
</td>
<td class="vert-align">
@Html.CheckBoxFor(modelItem => item.isSelected, new { @class = "mycheckBox" })
</td>
<td class="vert-align">
@Html.DisplayFor(modelItem => item.RoleDescription)
</td>
<td class="vert-align">
@Html.TextBoxFor(modelItem => item.Role, new { hidden = "hidden" })
</td>
</tr>
}
</table>
<div>
Roles selected:<input type="number" id="noSelected" value="0" />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Next" class="btn btn-default" />
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
var fld_CheckBoxSelected = document.getElementById("CheckBoxSelected");
var fld_noSelected = document.getElementById("noSelected");
$(function(){
$("input.mycheckBox").change(function(){
var isSelected = this.checked;
if (isSelected ) {
$("#noSelected").val( parseInt($("#noSelected").val())+ 1);
}
else
{
$("#noSelected").val( parseInt($("#noSelected").val()) - 1);
}
});
});
</script>
View model class:
public class RegisterEmployee_Step6Model
{
public byte Id { get; set; }
public int? Role { get; set; }
public bool isSelected { get; set; }
public string RoleDescription { get; set; }
public string IconLocation { get; set; }
}