In this article I will explain with an example, how to set type=number in TextBox using HTML.TextBoxFor and HTML.TextBox Helper methods in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Model

The Model class consists of following property.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Age.
    ///</summary>
    public int Age { getset; }
}
 
 

Controller

The Controller consists of following Action method.

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 and Html.TextBox helper methods.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        PersonModel person = new PersonModel
        {
            Age = 30
        };
 
        return View(person);
    }
}
 
 

View

HTML Markup

Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of two HTML INPUT TextBoxes created using Html.TextBoxFor and Html.TextBox Html Helper methods.

Html.TextBoxFor

The TextBox created using Html.TextBoxFor is set with following properties:
model property – The name of the property is set using Lambda expression.
htmlAttributes – An object that contains the HTML attributes to set for the element. In this case it is type=number.
 

Html.TextBox

The TextBox created using Html.TextBox is set with following properties:
name – The name of the form field. In Controller the TextBox value is captured using this parameter.
value – The value of the text input element.
htmlAttributes – An object that contains the HTML attributes to set for the element. In this case it is type=number.
@model HTML_TextBox_type_Number_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.Age, new { @type = "number" })
    @Html.TextBox("Age", 30, new { @type = "number" })
</body>
</html>
 
 

Screenshot

Rendered Page

Html.TextBox and Html.TextBoxFor set type=number in ASP.Net MVC
 
 

Downloads