@* checkboxes to select report opinions *@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<table>
<tr>
@{
int cnt = 0;
List<GovCAP.ViewModels.AuditReportOpinionData> AuditReportOpinionTypes = ViewBag.AuditReportOpinionTypes;
foreach (var auditReportOpinion in AuditReportOpinionTypes)
{
if (cnt++ % 3 == 0)
{
@:</tr><tr>
}
@:<td class="opiniontable">
<input type="checkbox"
name="selectedOpinions"
value="@auditReportOpinion.OpinionID"
@(Html.Raw(auditReportOpinion.Selected ? "checked=\"checked\"" : "")) />
@auditReportOpinion.OpinionID @: @auditReportOpinion.Description
@:</td>
}
@:</tr>
}
</table>
</div>
</div>
//construct empty entity object that we can pass to method to include releated records for report opinions
var legAuditReport = new LegAuditReport();
legAuditReport.LegAuditReportOpinions = new List<LegAuditReportOpinion>();
PopulateAuditReportOpinionData(legAuditReport);
// Constructs view model for report opinions for audit report passed as argument.
private void PopulateAuditReportOpinionData(LegAuditReport legAuditReport)
{
// Get all opinion types from db.
var allOpinions = db.AuditReportOpinionTypes;
// Get opinions selected for the audit report we're working with.
var reportOpinions = new HashSet<int>(legAuditReport.LegAuditReportOpinions.Select(c => c.AuditReportOpinionType.aroID));
var viewModel = new List<AuditReportOpinionData>();
foreach (var opinion in allOpinions)
{
// Construct the view model to include and opinion types from db and indicating which are selected for the report we're working with.
viewModel.Add(new AuditReportOpinionData
{
OpinionID = opinion.aroID,
AuditReportID = legAuditReport.larID,
Description = opinion.aroDescription,
Selected = reportOpinions.Contains(opinion.aroID)
});
}
ViewBag.AuditReportOpinionTypes = viewModel;
}
Anyway, I am doing something similar in an MVC 5 app. I have a ViewModel to present a list of optional checkboxes. In my Controller action I need to evaluate whether any were checked and, if so, which ones.
I pass in the checkbox as an array. Let me know if you would like to see any additional code, e.g. from the ViewModel that constructs the selectedOpinions or the View itself.
OM Gang
Open in new window