In this article I will explain with an example, how to make TextBoxes created using Html.TextBox and Html.TextBoxFor helper functions ReadOnly i.e. not editable in ASP.Net MVC Razor.
The TextBoxes can be made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html.TextBox and Html.TextBoxFor helper functions.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Model
Following is a Model class named PersonModel with a property i.e. Name.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
}
 
 

Controller
The Controller consists of the following Action methods.
Action method for handling GET operation
Inside this Action method, an object of PersonModel class is created and is returned to the View. The value of the Name property will be set in the TextBox created using Html.TextBoxFor helper function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        PersonModel person = new PersonModel
        {
            Name = "Mudassar Khan"
        };
 
        return View(person);
    } 
}
 
 
View
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
There are two TextBoxes. The TextBox for the Name value is created using Html.TextBoxFor function while the TextBox for the Country value is created using Html.TextBox helper function.
Both the TextBoxes are made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html.TextBox and Html.TextBoxFor helper functions.
@model TextBox_ReadOnly_MVC.Models.PersonModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @Html.TextBoxFor(m => m.Name, new { @readonly = "readonly" })
    @Html.TextBox("Country", "India", new { @readonly = "readonly" })
</body>
</html>
 
 
Screenshot
Html.TextBox and Html.TextBoxFor set ReadOnly in ASP.Net MVC
 
 
Downloads