1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Html helpers in MVC

Discussion in 'ASP.NET' started by Sagar Jaybhay, Apr 7, 2020.

  1. Sagar Jaybhay

    Sagar Jaybhay New Member

    Joined:
    Jan 28, 2019
    Messages:
    29
    Likes Received:
    17
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    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
    Code:
    <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
    Code:
    @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
    Code:
    @Html.TextBox(‘email’,’sagar@gmail.com’)
    
    If I want to set an initial style for textbox we can achieve this by using below way
    Code:
    @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.
    Code:
    @Html.TextBox(‘email’,’sagar@gmail.com’,new {@class=’class name’, @readonly=true});
    
    If we want to generate label
    Code:
    @Html.Label(‘firstname’,’sagar’)
    
    For password use below Html helper method to create password box
    Code:
    @Html.Password(“password”)
    
    If I want to generate textarea then for this also we have a method
    Code:
    @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
    Code:
    @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.
     
    shabbir likes this.

Share This Page