In this article I will explain with an example, how to set MaxLength property for TextBoxes created using Html.TextBox and Html.TextBoxFor helper functions in ASP.Net MVC Razor.
The MaxLength for TextBoxes is set using the HTML MaxLength 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 Mobile Number value is created using Html.TextBox helper function.
The MaxLength of both the TextBoxes is set using the HTML MaxLength attribute using the HtmlAttributes parameter in Html.TextBox and Html.TextBoxFor helper functions.
@model TextBox_MaxLength_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 { @maxlength = "15" })
    @Html.TextBox("MobileNo", "9999888877", new { @maxlength = "10" })
</body>
</html>
 
 
Screenshot
Html.TextBox and Html.TextBoxFor set MaxLength in ASP.Net MVC
 
 
Downloads