如何在Asp.Net MVC中创建自定义HTML帮助程序

时间:2013-09-16 09:37:39

标签: c# asp.net-mvc asp.net-mvc-3 razor

我是MVC的新手,并试图像这样编写一个示例html帮助器 这是我的html帮助程序代码。

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);

        }
    }
}

我在我的视图中使用如下

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

在视图的顶部我声明或引用名称空间和类名称,如上所述

并像@Html.Label("firstName", "First Name:")

一样使用它

但是当我调试代码时,我的扩展方法没有被命中。我能理解我做错了什么但是弄不清楚。所以请帮忙。感谢

4 个答案:

答案 0 :(得分:2)

如果我是你,我不会将其命名为Html Helper的原始名称。我会尝试类似的东西:

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

之后,只需包含名称空间(不是类的完整路径),样本:

@using MvcPractise.Extension

作为扩展方法,请在Html属性:

上使用它
@Html.CustomLabel("firstName", "First Name:")

答案 1 :(得分:1)

@Html.Label是内置助手,您需要尝试其他名称,例如@Html.LabelEx

将扩展方法重命名为某些内容,而不是标准库中的内容!它应该工作!

答案 2 :(得分:-1)

尝试如下,可能是因为Label的含糊不清 并且您使用的是Html助手而不是custom助手

的标签

@using MvcPractise.Extension

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

您的扩展方法:

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

    }

答案 3 :(得分:-1)

试试这个:

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

    }