What is the purpose of Html helpers in MVC By Sagar Jaybhay
In this article we will understand What is the purpose of Html helpers in MVC by Sagar Jaybhay .
Html helpers
What is an Html Helper? Html helper is a method that is used to render HTML content in a view. Html helpers are implemented using an extension method.
If you want to create an input text box with id=email and name is email
<input type=text id=email name=email value=’’/>
This is all Html we need to write by using the helper method it becomes so easy
@Html.TextBox(‘email’)
It will generate textbox control whose name is email.
If we want to assign the value of the textbox with some initial value then use below method
@Html.TextBox(‘email’,’sagar@gmail.com’)
If I want to set an initial style for textbox we can achieve this by using below way
@Html.TextBox(‘email’,’sagar@gmail.com’,new {style=’your style here’ , title=’your title here’});
Here style we pass is an anonymous type.
If we have reserved keyword like class readonly like that and we want to use this as an attribute how we will do this is doing below way means append with @ symbol with the reserved word.
@Html.TextBox(‘email’,’sagar@gmail.com’,new {@class=’class name’, @readonly=true});
If we want to generate label
@Html.Label(‘firstname’,’sagar’)
For password use below Html helper method to create password box
@Html.Password(“password”)
If I want to generate textarea then for this also we have a method
@Html.TextArea(“comments”,”,4,12,null)
In above code 4 is the number of rows and 12 is the number of columns To generate a hidden box
@Html.Hidden(“EmpID”)
Hidden textboxes are not displayed on the web page but used for storing data and when we need to pass data to action method then we can use that.
Is it possible to create our Html helpers in asp.net MVC? Yes, we can create our Html helpers in MVC. Is it mandatory to use Html helpers? No, we can use plain Html for that but Html helpers reduce a significant amount of Html code to write that view. Also, your code is simple and maintainable and if you required some complicated logic to generate view then this is also possible.
Subscribe to my newsletter
Read articles from Sagar Jaybhay directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Sagar Jaybhay
Sagar Jaybhay
I am Sr. Software Developer. I am having more than 7 yr's of experience in software field. i am full stack developer. Blogging is my hobby and Trading is my passion.