I have a Razor view which renders some drops downs using HTML helpers and others using jQuery DataTable,
<div class="form-group">
@Html.LabelFor(model => model.CarTyres, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.ListBoxFor(model => model.SelectedCarTyres, Model.CarTyres, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
@Html.ValidationMessageFor(model => model.SelectedCarTyres, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Drivers, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.ListBoxFor(model => model.SelectedDrivers, Model.Drivers, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
@Html.ValidationMessageFor(model => model.SelectedDrivers, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CarJacks, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
<table id="filtersTable">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
</tr>
</thead>
</table>
</div>
@Html.ValidationMessageFor(model => model.CarJacksCheckBox, "", new { @class = "text-danger" })
</div>
In my model , I am setting the required to true so that when I check Model.IsValid()
will return false if any of those items are not set, and that works fine.
public class ReportViewModel
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
[Required]
public ICollection<int> SelectedCarTyres { get; set; }
public IEnumerable<SelectListItem> CarTyres { get; set; }
[Required]
public ICollection<int> SelectedDrivers { get; set; }
public IEnumerable<SelectListItem> Drivers { get; set; }
public IEnumerable<CarJackViewModel> CarJacks { get; set; }
[Required]
public string SelectedSampleTime { get; set; }
public IEnumerable<SelectListItem> SampleTimes { get; set; }
[Required]
public IEnumerable<int> CarJacksCheckBox { get; set; }
}
To make javascrip data tables required , I copied the vallidation attributes on checkbox(es) like following:
$('#filtersTable').DataTable(
{
"iDisplayLength": 25,
"ajax": {
"url": "/CarJacks/Loaddata",
"type": "GET",
"datatype": "json"
},
"columns": [
{
"data": "IsSelected",
"render": function (data, type, row) {
if (type === 'display') {
return '<input type="checkbox" name="CarJacksCheckBox" class="editor-active" data-val="true" data-val-required="The CarJacks field is required.">';
}
return data;
}
],
"rowCallback": function (row, data) {
//Removed for Brevity
}
}
);
But still , I am not getting any client side validation when none of the CarJackCheckBox are selected.
Though (ModelState.IsValid)
is returning false, $(form).valid()
returning true and hence no errors on client side.
Which piece am I missing ?