Why don't my HtmlHelper extensions work?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 00:42:24

Check to make sure that the namespace of your extensions is accessible to our view. You need either this in your view:

<%@ Import Namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"%>

or this in your web config namespaces section:

<add namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"/>

If you're using strongly typed views, and your extension method is extending HtmlHelper<object>, it's not going to find the extension. You'd have to create a generic extender to extend HtmlHelper<T>.

public static string IncludeScript<T>(this HtmlHelper<T> html, string url) {
   return "<script type=\"text/javascript\" src=\"" + url + "\"></script>";
}

Then you'll see your extender method show up.

I hope that helps.

Make sure to have an import directive to your extensions methods namespace in your page.

Otherwise, Visual Studio might be able to see but your website won't be able to.

Are you sure the compiler is set to .NET Framework 3.5? This happened to me when I inadvertently set the compiler to .NET Framework 2.0

In the IncludeScript method make sure that what you are extending is System.Web.Mvc.HtmlHelper. It's possible there is an HtmlHelper in some other namespace.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!