简体   繁体   中英

How create Custom HTML Helper in Asp.Net MVC

i am new in MVC and trying to write a sample html helper like this way here is my html helper code.

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

        }
    }
}

i use it as follows in my view like

@using MvcPractise.Extension.LabelHelper
@model MvcPractise.Models.EmployeeModel

at the top of the view i declare or refere the namespace and class name like above

and use it like @Html.Label("firstName", "First Name:")

but when i debug the code the my extension method is not getting hit. i could understand that i am doing something wrong but could not figure out. so please help. thanks

If I were you, I would not name it as the original name from the Html Helper. I would try something like:

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

After it, just include the namespace (not the entire path to the class), for sample:

@using MvcPractise.Extension

And as the extension method, use it on Html property:

@Html.CustomLabel("firstName", "First Name:")

@Html.Label is a built in helper, you need to try another name, like @Html.LabelEx

Rename your extension method to something, that is not in the standard library! And it should work!

Try as follows it may be because of ambuiguity of Label and you are using the label of Html helper and not custom helper

@using MvcPractise.Extension

@LabelHelper.LabelCustom("firstName", "First Name:")

Your extension method:

    public static string LabelCustom(string target, string text)
    {
        return String.Format("<label for='{0}'>{1}</label>", target, text);

    }

Try this:

  public static string Label(string target, string text)
    {
        return String.Format("<label for='{0}'>{1}</label>", target, text);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM