Monday, June 4, 2012

MVC-HTML Helper




Using HTML Helper :

The HtmlHelper class provides methods that help you create HTML controls programmatically. 

All HtmlHelper methods generate HTML and return the result as a string. 

HtmlHelper class is designed to generate UI. It should not be used in controllers or models.

Some example of ASP.NET MVC framework HTML Helpers below
  1.  Html.TextBox()
  2. Html.ActionLink()
  3. Html.Hidden()
  4. Html.BeginForm()   : The Html.BeginForm() Helper method is used to create the opening and closing HTML <form> tags.  Notice that the Html.BeginForm() method is called within a using statement. The using statement ensures that the <form> tag gets closed at the end of the using block.
  5. Html.EndForm()
  6. Html.CheckBox()
  7. Html.ListBox()
  8. Html.Password()
  9. Html.RadioButton()
  10. Html.DropDownList()
  11. Html.TextArea()
  
Click here for full List of Html helpers 



Note : HTML Helper Html.TextBox() is rendered with <%= %> tags instead of <% %> tags

e.g :
<h2><%= Html.Encode(ViewData["parameter"])%></h2>
<br /><br />

<% using(Html.BeginForm("Input", "Home")) %>
<% { %>
    Enter your name: <%= Html.TextBox("name") %>
    <br /><br />
    Enter a password: <%= Html.Password("pass") %> (Not actually used.)
    <br /><br />
    Select your country:<br />
    <%= Html.RadioButton("Country", "India", true) %> Blue <br />
    <%= Html.RadioButton("Country", "USA", false)%> Purple <br />
    <%= Html.RadioButton("Country", "UK", false)%> Red <br /> 
    <br /><br />
    <%= Html.CheckBox("Asp") %> I know Asp.net<br />
    <%= Html.CheckBox("csharp") %> I like csharp.<br />
    <%=  Html.CheckBox("MVC") %> I work  wirth MVC.<br />
    <br /><br />
    <input type="submit" value="Submit" />
<% } %>

Output :

Create Html helpers programmatically :


//*** Create helpers Class with Static method returning string

Step 1 -  Create folder helpers in project.
Step 2 -  Create following Class in Helper folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcTextApplication.Helpers
{
    public class GenericHelperClass
    {
        public static string Label_generic(string target, string text)
        {
            return String.Format("<label for='{0}'>{1}</label>", target, text);
        }  

    }
}

Note :  import Name space in View page : <%@ Import Namespace="MvcTextApplication.Helpers" %>
HTML :    <%=   GenericHelperClass.Label_generic("firstName", "First Name:") %>
Out Put:  First Name:

HTML Helpers with Extension Methods:


HTML helpers with extension methods work like normal MVC framework Helpers.
Extension methods enable you to add new methods to an existing HtmlHelper class represented by a view's Html property.  
For this purpose we need to do some changes in our class
1.       Import namespace  using System.Web.Mvc;
2.       Declare class as static.
3.       Pass class  HTMLHelper as parameter with this keyword. The first parameter of an extension method indicates the class that the extension method extends.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcTextApplication.Helpers
{
    public static class GenericHelperClass
    {
        public static string Label_generic(this HtmlHelper helper, string target, string text)
        {
            return String.Format("<label for='{0}'>{1}</label>", target, text);
        }  

    }
}

HTML  <%=     Html.Label_generic("firstName", "First Name:") %>
Out Put:  First Name:


HTML Helpers WITH TagBuilder Class

The TagBuilder class enables you to easily build HTML tags and comes under System.Web.Mvc namespace.
 It has five methods:
  • AddCssClass() - Enables you to add a new class=”” attribute to a tag.
  • GenerateId() - Enables you to add an id attribute to a tag. This method automatically replaces periods in the id (by default, periods are replaced by underscores)
  • MergeAttribute() - Enables you to add attributes to a tag. There are multiple overloads of this method.
  • SetInnerText() - Enables you to set the inner text of the tag. The inner text is HTML encode automatically.
  • ToString() - Enables you to render the tag. You can specify whether you want to create a normal tag, a start tag, an end tag, or a self-closing tag.
The TagBuilder class has four important properties:
  • Attributes - Represents all of the attributes of the tag.
  • IdAttributeDotReplacement - Represents the character used by the GenerateId() method to replace periods (the default is an underscore).
  • InnerHTML - Represents the inner contents of the tag. Assigning a string to this property does not HTML encode the string.
  • TagName - Represents the name of the tag.

Example : 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcTextApplication.Helpers
{


    //GenericHelperClass class contains two static overloaded methods named GenerateImage.
    //When you call the GenerateImage() method, you can pass an object which represents a set of HTML attributes or not.
    public static class GenericHelperClass
    {

        public static string GenerateImage(this HtmlHelper helper, string id, string url, string alternateText)
        {
            return GenerateImage(helper, id, url, alternateText, null);
        }

        public static string GenerateImage(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
        {
            // Create tag builder
            var builder = new TagBuilder("img");
            // Create valid id
            builder.GenerateId(id);

            // Add attributes
            builder.MergeAttribute("src", url);
            builder.MergeAttribute("alt", alternateText);
            //The MergeAttributes() method accepts a Dictionary<string,object> parameter.
            //The The RouteValueDictionary class is used to convert the Object representing
            //the collection of attributes into a Dictionary<string,object>.
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));         
            // Render tag
            return builder.ToString(TagRenderMode.SelfClosing);
        }

        public static MvcHtmlString ActionLinkWithSpan(this HtmlHelper html, string linkText,string actionName, string controllerName, object htmlAttributes)
        {
            RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
            TagBuilder linkTag = new TagBuilder("a");
            TagBuilder spanTag = new TagBuilder("span");
            spanTag.SetInnerText(linkText);
            // Merge Attributes on the Tag you wish the htmlAttributes to be rendered on.
            //linkTag.MergeAttributes(attributes);
            spanTag.MergeAttributes(attributes);
            UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
            linkTag.Attributes.Add("href", url.Action(actionName, controllerName));
            linkTag.InnerHtml = spanTag.ToString(TagRenderMode.Normal);
            return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.Normal));
        }
    }
}
  <!-- Calling helper without HTML attributes -->
    <%= Html.GenerateImage("Image1", ResolveUrl("mvc-architecture.png"), "Model-View-Controller Image")%>


    <!-- Calling helper with HTML attributes -->
    <%= Html.GenerateImage("Image2", ResolveUrl("mvc-architecture.png"), "Model-View-Controller Image", new { border = "2px", height = "80px"})%>

      <!-- Calling helper Action Link -->
    <%: Html.ActionLinkWithSpan("Navigate Here", "method1", "Experiments", new { id="myLink", @class="link" })%>




         

No comments :

Post a Comment