Briefly explain to me how we can generate TextArea control using HtmlHelper in razor view with an example.
How we will generate TextArea control using HtmlHelper in razor view?
6177
15-Feb-2020
Updated on 15-Feb-2020
Nishi Tiwari
15-Feb-2020This HtmlHelper class includes the two extension methods to generate a multiline <textarea> element in the razor view that is TextArea() and TextAreaFor() by default, it creates textarea with rows=2 and cols=20.
Now we will use the following Student model with the TextArea() and TextAreaFor() method.
Example of Student Model
TextArea()
This Html.TextArea() method creates <textarea rows="2" cols="20" > element with the specified name, the value and html attributes.
TextArea() method Signature
This TextArea() method is a loosely typed method because the name parameter is a string and the name parameter can be a property name of the model object and also it binds a specified property with the textarea and so it automatically displays a value of the model property in a textarea and visa-versa.
Example of Html.TextArea() in Razor View
Html Result:
In the given above example, the first parameter is the "Description" property of the Student model class which will be set as a name & id of textarea, the second parameter is a value that displays in a textarea, and the third parameter will be set as a class attribute. The HTML attributes parameter is an object type, so it can be anonymous object and attributes name will be its properties starting with @ symbol.
Example of Html.TextArea() in Razor View
@Html.TextArea("myTextArea", "This is value", new { @class = "form-control" })Html Result:
This above example would generate elements as shown given below.
TextAreaFor
The TextAreaFor helper method is a strongly typed extension method, it generates a multiline <textarea> element for the property in the model object specified using a lambda expression. This TextAreaFor method binds a specified model object property to the Textarea element and so it automatically displays a value of the model property in a textarea and visa-versa.
TextBoxFor() method Signature
Example of TextAreaFor() in Razor View
Html Result:
The given above example, the first parameter in TextAreaFor() method is a lambda expression which specifies the model property to be bound with the textarea element and it generates <textarea> element with id & name set to property name – Description and the value of textarea will be set to the value of a Description property.