Saturday, 7 March 2020

Create Label Required Html Helper with Required Symbol





Create Label Required Html Helper with Required Symbol


In this article you will learn followings things:
  • What is Html Helper in Asp.Net MVC and types?
  • Why we need custom Html Helper?
  • How to create Custom Html Helper?
  • Step by Step Implementation


What is HTML Helper Asp.Net MVC and types ?
HtmlHelper is class inside namespace System.Web.Mvc. This class handle and responsible to generate HTML tag in ViewEngine.

There are two types of HTML Helper:
Non-Strongly Typed Html Helper (Basic Html Helper)
Strongly Typed Html Helper

Example:
@Html.Label  ---- Non-Strongly Typed Html Helper Example

@Html.LabelFor ---- Strongly Typed Html Helper Example

Why we need custom Html Helper?
You can design your own html helper as per requirement those html helper called Custom Html Helper.

How to create Custom Html Helper?
Custom creation of Html Helper is very simple. We have to create only class file with Static Class   and Static Method.

Example:
public static class CustomerHelper
{
public static IHtmlString LabelRequired(this HtmlHelper helper , string LabelText, string Symbol, string HtmlClass)
{

}
}

 Create an new project called “AspNetMvc”




In below dialog box do the followings:
SR.
NO.
DESCRIPTION
1
Select MVC Template.
2
Confirm or Check MVC check box selected .
3
Click Change Authentication button select NO AUTHENTICATION value.




Wait Visual Studio will create project as per above selections.



Default view of SOLUTION EXPLORER.


































Add new class called “CustomHelper”, Now right click on Project  ADD-->CLASS











While you tried HtmlHelper in Parameter section its show RED UNERLINE.
Red underline because HTML HELPER using namespace System.Web.Mvc.


CustomHelper.cs  Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetMvc
{
    public static class CustomHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper">Html Helper</param>
        /// <param name="DisplayText">Text To Display</param>
        /// <param name="Symbol">To Display Symbol like *</param>
        /// <param name="HtmlClass">Class name </param>
        /// <returns></returns>
        public static IHtmlString LabelRequired(this HtmlHelper helper, string DisplayText, string Symbol, string HtmlClass)
        {
            string LabelRequiredString = string.Empty;

            //Tag To build
            TagBuilder tb = new TagBuilder("label");

            //Assign Css Class
            tb.AddCssClass(HtmlClass);

            //Add HTML
            tb.InnerHtml = DisplayText + "<span style='color:red;font-size:20px;'>" + Symbol + "</span>";

            return new MvcHtmlString(tb.ToString());
        }

    }
}


Now switch to Models folder, right click on Model folder and add new model called “MemberModel”
























MemberModel.cs code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AspNetMvc.Models
{
    public class MemberModel
    {
        [Required(ErrorMessage ="Full name required")]
        public string FullName { get; set; }

        public string Address { get; set; }

        public string Phone { get; set; }

        [Required(ErrorMessage = "Email required")]
        public string Email { get; set; }

    }
}

Now switch to Controllers folder, double click on HomeController and add new ActionResult called NewMember()
















Default Code generated using Scaffolding:
@model AspNetMvc.Models.MemberModel

@{
    ViewBag.Title = "NewMember";
}

<h2>NewMember</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>MemberModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


After using Customer Helper:
@Html.LabelRequired

Example:
 @Html.LabelRequired("Full Name", "*", "control-label col-md-2")

NewMember.cshtml code:
@model AspNetMvc.Models.MemberModel

@{
    ViewBag.Title = "NewMember";
}

<h2>NewMember</h2>

@using AspNetMvc

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>MemberModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelRequired("Full Name", "*", "control-label col-md-2")
            <div class="col-md-10">
                
                @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelRequired("Email", "*", "control-label col-md-2")
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


OUTPUT: 




















Happy Coding..





No comments:

Post a Comment

Please, Write your valuable comments..