Create a Textbox in ASP.NET MVC
The HtmlHelper class includes two extension methods TextBox()
and TextBoxFor<TModel, TProperty>()
that renders the HTML textbox control <input type="text">
in the razor view.
It is recommended to use the generic TextBoxFor<TModel, TProperty>()
method, which is less error prons and performs fast.
We will use the following Student
model class throughout this article.
public class Student
{
public int StudentId { get; set; }
[Display(Name="Name")]
public string StudentName { get; set; }
public int Age { get; set; }
public bool isNewlyEnrolled { get; set; }
public string Password { get; set; }
}
Html.TextBoxFor()
The TextBoxFor<TModel, TProperty>()
is the generic extension method that creates <input type="text">
control.
The first type parameter is for the model class, and second type parameter is for the property.
public static MvcHtmlString TextBoxFor<TModel,TProperty> (this HtmlHelper<TModel>> htmlHelper, Expression<Func<TModel,TProperty>> expression, object htmlAttributes);
There are other overloads of the TextBoxFor()
method. Visit docs.microsoft.com to know all the overloads of TextBoxFor() method.
The following example shows how to render a textbox for the StudentName
property of the Student
model.
@model Student
@Html.TextBoxFor(m => m.StudentName)
In the above example, the lambda expression m => m.StudentName
specifies the StudentName
property to bind with a textbox.
It generates an input text element with id and name attributes, as shown below.
<input id="StudentName" name="StudentName" type="text" value="" />
The following example renders a textbox with the class
attribute.
@model Student
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })
<input class="form-control" id="StudentName" name="StudentName" type="text" value="" />
Html.TextBox()
The TextBox()
method creates <input type="text" > HTML control with the specified name, value, and other attributes.
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes)
Visit docs.microsoft.com to know all the overloads of TextBox() method.
The TextBox()
method is a loosely typed method because the name parameter is a string. The name parameter can be a property name of a model object. It binds specified property with a textbox. So it automatically displays the value of the model property in a textbox and visa-versa.
@model Student
@Html.TextBox("StudentName")
<input id="StudentName" name="StudentName" type="text" value="" />