In this article I will explain with an example, how to make CheckBox ReadOnly in ASP.Net MVC Razor.
By default, CheckBox cannot be made ReadOnly and hence using JavaScript it is made Non-Clickable.
Model
The following Model class consists of one property HasPassport to which the Display Data Annotation attribute has been applied.
public class PersonModel
{
[Display(Name = "Do you have Passport?")]
public bool HasPassport { get; set; }
}
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of the following two HTML Helper functions: -
1. Html.CheckBoxFor – Creating a CheckBox for the Model property.
2. Html.LabelFor – Displaying the Model property name.
The CheckBox is made ReadOnly by making it Non-Clickable by adding JavaScript OnClick event handler and returning False.
@model CheckBox_ReadOnly_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<table>
<tr>
<td>@Html.CheckBoxFor(m => m.HasPassport, new { @onclick = "return false" })</td>
<td>@Html.LabelFor(m => m.HasPassport)</td>
</tr>
</table>
</body>
</html>
Screenshot
Downloads