.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Creating HTML Helpers with Extension Methods

Posted By:      Posted Date: October 18, 2010    Points: 0   Category :ASP.Net

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



Above is my html helper class.

<%= Html.Label("first name", "First name") %>

This is how I use it.

Now while using it I am getting an error which says, "  No overload for method 'Label' takes '2' arguments ", where as this link ( http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs) says to do it exactly as i did.

Can anyone please guide where I am going wrong.



View Complete Post

More Related Resource Links

The Decorator Pattern & Extension Methods

The decorator pattern provides a formal way to add new functionality to an existing type, without sub-classing. First question: What is wrong with classical inheritance? In and of itself, nothing is wrong with the good old Is-A relationship. It is very common to derive a new class from an existing base class in order to override a few virtual members, and add a pinch of new functionality.

The Decorator Pattern & Extension Methods

Numerous design patterns exist in the software world today, and ultimately nothing is preventing you from making your own (if people buy into it or not is another question). Furthermore, there is no 'master list' of patterns that all developers agree upon. While this is true, if you pick up any book on the subject, you will find a set of very common patterns most programmers agree are very useful. Many of these patterns were first formalized in the seminal book on the subject, Design Patterns: Elements of Reusable Object-Oriented Software (aka, the Gang of Four [GOF] book; not to be confused with the UK punk band of the same name).

Basic Instincts: Extension Methods


This column discusses one of the new features of Visual Basic 2008-Extension Methods. This powerful new feature was introduced to support LINQ. See what extension methods are, how to apply them yourself, and get some great usage tips.

Adrian Spotty Bowles

MSDN Magazine November 2007

Delegates in .NET: A Primer on Creating Type-Safe References to Methods in Visual Basic .NET


Delegates, new in Visual Basic .NET, are type-safe, object-oriented references to methods. By using delegates, you make your methods accessible to others and therefore more extensible. This article provides an introduction to delegates, their benefits, and how they are used.Here the author shows you how to declare, create, and use delegates to invoke instance and shared methods at run time, and how to implement delegates as properties. He then goes on to provide examples of how delegates are used for callback functionality and explains the relationship between delegates and events. Finally, the article provides a glimpse at how delegates are implemented in intermediate language code by the Visual Basic .NET compiler.

Jesse Liberty

MSDN Magazine February 2003

Html Helpers and Exceptions



I have been working in a few MVC HTML Helpers. For example:

    public static MvcHtmlString GoogleAnalytics(this HtmlHelper helper, String account, String url) {
      // ...

If account or url are null should I trhow an exception? Or render an empty string? Or render an Html comment in the view?

What is the recommended approach for this?



System.EntryPointNotFoundException: Entry point was not found. when unit testing html helpers


I'm trying to unit test a very simple html helper but keep getting the following exception:

System.EntryPointNotFoundException: Entry point was not found.

public static string AdditionalUsersDropDownList( this HtmlHelper helper, int additionalUsers )


Dictionary<int, string> items = new Dictionary<int, string>( );

items.Add( 0, "None" );

for ( int i = 1; i <= 30; i++ )


items.Add( i, i.ToString( ) );


SelectList list =  new SelectList( items, "Key", "Value", additionalUsers );

return helper.DropDownList( "AdditionalUsers", list );


Creating a PrintDocument from html

Hi, I'm trying to create a custom print preview for internet explorer.  Currently my program is using print templates but the functionality that I need can't be provided by this outdated method.  Instead I'm looking to implement a custom print preview in .net such as the example given here http://www.codeproject.com/KB/printing/CoolPrintPreviewDialog.aspx. However, pretty much every custom print preview example I have seen requires that the PrintDocument be provided and as of right now I have no idea how to obtain a PrintDocument from an html file or webbrowser control.  So my question is, is there a way to obtain a PrintDocument that has rendered html?  Is there a better method to writing a custom print preview for web pages? Thanks for your time!

Help creating HTML table from dataTable when every nth dataTable row = 1 html table row... C#

Hello, Im trying to create an html table from data that is in a dataTable but Im having trouble coming up with the right logic. Every 3 rows in the dataTable needs to be 1 row in the html table.  Ive tried using foreach through the datatable with a modulus to determin every third dataTable row but i still run into snags because i am building the table using objects rather than using concatenated strings..(example TableRow tr = new TableRow  etc...). I cant add the cells to the rows when the row is only created in an if statement etc. Can someone post a good example in c# of how they would achieve this. The amount of data in the dataTable could change from time to time so the code cant rely on a pre determined size, unless you just need the total rows and columns, that can be dtermined when the dataTable is filled from the sqlDataReader. <table><tr><td>dataTable row 1 values</td><td>ataTable row 2 values</td><td>dataTable row 3 values</td></tr> <tr><td>dataTable row 4 values</td><td>dataTable row 5 values</td><td>dataTable row 6 values</td></tr>   Any help and example would be great. Ive been able to do similar tables in other apps but thats only when I use concatenated text strings to build the html table. Im trying to stay away from that this time

Custom Field - SP is creating HyperLinks and using HTML entities

Hello. I'm seeking help with a problem related to a custom field in SharePoint 2010. Our Custom Field builds upon (extends) the SPFieldMultiLineText field. Data saved to our Custom Field is being processed by SharePoint before it is sent to the client. For example < and > is replaced by HTML entities (&lt; and &gt;). Text such as http://bing.com and mail@bing.com is automatically being converted to hyper links (<a href="mailto:mail@bing.com">mail@bing.com</a>). Is it in any way possible to have SharePoint deliver the data as it was stored in the custom field? We don't want it to replace HTML with HTML entites, nor should it create hyperlinks automatically. I have attached our XSL file below. <xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Micros

If-Else condition for ActionLink in Html Extension


In my code, I'm trying to write "if" condition in HTML.Helper instead of view.
Can you please tell me what mistake i'm doing?

Code on Controller

public static string IsSetup(this HtmlHelper helper, AModel aModel) 
string actionLink = string.Empty; 

 if (aModel.IsSetup) 
 { actionLink = "Html.ActionLink(\"" + "Continue for Setup\"" + "," + "\"Setup\"" + "," + "\"SetupController\") "; return actionLink; } 

 { actionLink = "Html.ActionLink(\"" + "Continue for Index\"" + "," + "\"Index\"" + "," + "\"SetupController\") "; 

 return actionLink; 


Code on View
        Please click to
        <%= Html.IsSetup(Model)%>
  // I'm expecting, <%= Html.ActionLink("Continue for Setup", "Setup", "SetupController") %>
  // but it renders as a TEXT like,  Please click to <%= Html.ActionLink("Continue for Setup", "Setup", "SetupController") %>

Extension methods and viewstate


Hi all,

I am creating 2 extension methods for a textbox, which need to store a value and get the value, same like property, unfortunately dotnet 3.5 doesnt support extension property, so created two extension method for set and get, I am so confusing where should I store the value, like session, cache or anything else, but my recommendation to store in the viewstate object. how can I store value to viewstate. 

example my code look like

public static class clsExt
    public static bool getValue(this TextBox tb)

        return (bool)Viewstate[tb.ID];

    public static void setValue(this TextBox tb, bool value)

        Viewstate[tb.ID] = value;


Its not good idea to store session or cache, bcoz its should store only in the pagelevel, how can do this? How other textbox property storing? Could any one help on this issue please?

Thanks in advance.

MVC2: Change the default generated HTML when creating a strongly typed view


Is there any way to change the HTML that is generated by default when you create a strongly typed view in MVC2?

I currently get a structure like this:

            <div class="editor-label">
                <%: Html.LabelFor(model => model.category_id) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.category_id) %>
                <%: Html.ValidationMessageFor(model => model.category_id) %>

I want to change it to a structure like this:

                <div><%: Html.ValidationMessageFor(model => model.user_login) %></div>
                <div><%: Html.LabelFor(model => model.user_login) %></div>
                <div><%: Html.TextBoxFor(model => model.user_login) %></div>

stupid -- why does model.Model break Html helpers?



This code in an aspx file:

      <%: Html.TextBoxFor(model => model.Model) %>

Breaks the page with the following error - which I think is stupid as Model is a property of my Product Entity and relates to the Model of the product (e.g. Make, Model, Year). If I remove this model.Model reference the rest of the Product properties render as expected. I am stuck with renaming my property?

Value cannot be null or empty.
Parameter name: name

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Argu

Creating datagrid in HTML in MVC 2


Can anybody provide me with an example or link to an example of a simple way of showing data in MVC 2 in a grid?  I am not looking for any edit/delete etc functionality, just a simple full example showing the HTML and code necessary to access data and then pass it to and display it in a view.


Many thanks,


what is Extension Methods and when, where we will we use it


what is Extension Methods and when, where we will we use it

interesting problem about @ and extension methods.


Note , that i'm new to c# so it might not be a problem.

first , what is the exact meaning of @ in Razor ?

does it mean WebPage.Response.Write ?

next, i designed an extension method to WebPage ( by the way that is the coolest feature ever in c# )

in my Razor code , to use it in a webpage , i must write @this.MyExtensionMethod() instead of @MyExtensionMethod().

So why is it?  because @this.MyExtensionMethod() and @MyExtensionMethod() should be the same ?

here is my extension method :

using System;
using System.Web;
using System.Web.WebPages;

namespace MyExtenstionMethods{

	public static class Utility{

	    // make the page to render optional
		public static dynamic RenderOptionalPage(this WebPage Webpage ,string page="",params object[] data){

				return Webpage.RenderPage(page,data);
            }catch(HttpException ex){
                return new HtmlString("<!-- page not found -->");


Creating dynamic elements in an html table


I need to create 3 buttons in addition to 2 text values (which come out fine) in a row for a table.

However, the buttons are coming out as straight input text fields even though I specifiy  "button" as the type for the td attribute.

Below is my js.

How can I set up these buttons as actual buttons instead of input text fields? Notice the boldfaced code below which is coming out as just input text boxes instead of buttons.

    var tr = document.createElement('tr');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    var td5 = document.createElement('td');

    //Up button

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend