Tuesday, November 12, 2019

Html Helper Controls in Asp.net MVC


HtmlHelperControls:

Html helper are nothing but it’s like a C# method for Rendering html Controls.

Html Helper is a method  that is used to Render the content in a view. Html Helpers are implemented as extension method.

Two types of Html Helper controls


     1. Strongly typed:  
  •     It is adding end “for” like TextBoxFor, RadioButtonFor etc.
  • It’s considered about the model, the model only verifies the controller, the controller getting value coming or not.
  • It’s checks validations and the value coming correct or not.
2. Loosely typed
  • It is nothing but like Textbox, Label, Radio Button etc.
  • It’s doesn’t consider about the model
  • Advantage: its jest gives the name and based on that it creates name property for us but it doesn’t check the value correct or wrong.

TextBox:

Its show to display the value on textbox

@Html.TextBox("FirstName","Supriya")

                                  output

In output page u right click -> View page source

<input id="FirstName" name="FirstName" type="text" value="Supriya" />                                         

                         

After passing the value, how we can give the css class like below

            This is First Parameter    This is Second Parameter

@Html.TextBox("FirstName","Supriya", new {@style ="background-color:red;color:white",@class="form-control"})

                                     This is Third Parameter    
            

@class="form-control" this is bootstrap class so, in case the layout page is null the bootstrap class is not working that way u can change the layout URL like below

Layout = "~/Views/Shared/_Layout.cshtml";


First Parameter: The first parameter it’s create will be id, name, type

Second Parameter: it’s used to give values.

Third Parameter: it’s given to design pattern  

Password:

                   @Html.Password("PassWord","Jack")

                                         output

                                   
       

Here the first parameter create type = Password so, it gets *****


RadioButton:

        @Html.RadioButton("Gender", "Male")<span>Male</span>

        @Html.RadioButton("Gender", "FeMale") <span>FeMale</span>   
                               
        

U must and should give first parameter same like “Gender”, then that one treated as group name.

Label:



        @Html.Label("Select Country")


DropDownList: 

        @Html.DropDownList("Country", new List<SelectListItem>{

            new SelectListItem{Text="India", Value="1"},

            new SelectListItem{Text="Us", Value="2"},

            new SelectListItem{Text="China", Value="3"}

        },"Select Country")                                       



Incase you select any field in the dropdown box, then go and write selected=true for list it’s shown below


       new SelectListItem{Text="India", Value="1", Selected=true},

                                           



Any Html elements first parameter will be defined ID, name and type.

I will take data from database using database first approach for dropdownlist

Right click on Model and add entity like DepartmentModel

Create obj for MvcApplicaionEntities class(deparmentContext.cs) in DefaultController page                

Now take a ViewBag to fill the data from database to dropdownlist so, you write below code in Employeecontroller.cs page

        public ActionResult HtmlHelperControls()

        {

            ViewBag.Dept = new SelectList(db.Departments, "DeptId", "DeptName");

            return View();

        }                            



Now add dropdown list in view(HtmlHelperControls.cshtml) page.



@Html.DropDownList("Department") : in this Department is viewbag name




@Html.DropDownList("Department","Select Department")

In case u want selected particular department in dropdownlist Add below code in EmployeeController.cs page

            ViewBag.Dept = new SelectList(db.Departments, "DeptId", "DeptName",4);


Strongly typed Html Helper controls:

These helper methods create the output HTML elements based on model properties. The property to be used to create the HTML is passed to the method as a lambda expression.

first we want to define Model class in view page like below
@model MVC7AmWarriorBatch.Models.EmployeeModel

@Html.LabelFor(Model => Model.EmpName)
@Html.TextBoxFor(Model=>Model.EmpName) 

EmpName  

There is no difference between TextBox and TextBoxFor in design the only difference is:

1.If you give wrongly name (EmpNames) in TextBoxFor that name also throw an error.

2.They check validation through model class the employee name is correct or not.  
In output showing like below

Validations:

So, we can do particular operation near EmpName in Model(EmployeeModel.cs) page.

First u adds the namespace
using System.ComponentModel.DataAnnotations;

        [Display(Name ="Employee Name")]
        public string EmpName { get; set; }

Creating Custom Html Helpers:

If we want to create our own HTML helpers than that can also be done very easily.

There are 3 types of creating custom html helpers.
  1. ·   Static method
  2.     Extension method
  3.     @helper class

Creating Static Method:

we can simply create a static class with static method which will return the HTML string to be used at the time of rendering.

First in your solution add folder like CustomHelpers -> right click on folder -> Add ->Class(HtmlHelpersExample.cs) -> ok

Then copy below code in HtmlHelpersExample.cs page
  
namespace MvcProject.CustomHelpers
{
    public static class HtmlHelpersExample
    {
        public static IHtmlString MyLabel(string content)
        {
            string htmlstring = String.Format("<label>{0}</label>", content);
            return new HtmlString(htmlstring);
        }
    }
}
If you create your own label by using IHtmlString method only

How to call the Customize Static label in View folder HtmlHelperControls.cshtml page

@using MvcProject.CustomHelpers;
@HtmlHelpersExample.MyLabel("I accept the Argeement.")
I accept the Argeement. Output

Extension method:

In this approach we will write a simple extension method for the built-in html helper class. this will enable us to use the same Html object to use our custom helper method.

The extension method is will not appear as parameter, but we are going to extended particular method.

Then copy below code in HtmlHelpersExample.cs page in CustomHelpers folder

using System.Web.Mvc;
public static IHtmlString createUrControl(this HtmlHelper helper, string content)
{
    string htmlstring ="<input type="+content+">";
    return new HtmlString(htmlstring);
}
In above code HtmlHelper is a free define class inthis class only we use @Html class

How to call the Customize Controls in View folder HtmlHelperControls.cshtml page

        @Html.createUrControl("file")
        @Html.createUrControl("text")
        @Html.createUrControl("button")


Helper Object:

 We need to write this method in the view itself.

Copy below code in HtmlHelperControls.cshtml page
@helper labelbyrazzorcode(string content)
{
 <label>@content</label>  
 }
@labelbyrazzorcode("hi this is ali")
Output is show like below
                        hi this is ali

















No comments:

Post a Comment