12
1
using System;
2
using System.ComponentModel.DataAnnotations;
3
4
namespace MvcRequiredCheckbox
5
{
6
public class SampleViewModel
7
{
8
[Display(Name = "Terms and Conditions")]
9
[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
10
public bool TermsAndConditions { get; set; }
11
}
12
}
62
1
@model MvcRequiredCheckbox.SampleViewModel
2
3
<!DOCTYPE html>
4
<html lang="en">
5
<head>
6
<title>ASP.NET MVC - Required Checkbox with Data Annotations</title>
7
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
8
<style type="text/css">
9
.field-validation-error {
10
color: #ff0000;
11
display: block;
12
}
13
</style>
14
</head>
15
16
<body>
17
<div class="container">
18
<div class="col-md-6 col-md-offset-3">
19
<h1>ASP.NET MVC - Required Checkbox with Data Annotations</h1>
20
21
@using (Html.BeginForm())
22
{
23
<div class="form-group">
24
@Html.CheckBoxFor(x => x.TermsAndConditions)
25
1
using System;
2
using System.Web.Mvc;
3
using System.Collections.Generic;
4
5
namespace MvcRequiredCheckbox
6
{
7
public class HomeController : Controller
8
{
9
public ActionResult Index()
10
{
11
return View();
12
}
13
14
[HttpPost]
15
public ActionResult Index(SampleViewModel viewModel)
16
{
17
if(!ModelState.IsValid)
18
{
19
return View(viewModel);
20
}
21
22
return Content("Success");
23
}
24
}
25
}