I am trying to register a Custom MVC HtmlHelper extension.
I have created the appropriate static class and static method for my extension method but how do I register/import/use that namespace in my view so it shows up as an extension method for some given method, for @Html.SomeMethod
In Asp.Net WebForms I can simply add:
<%@ Import Namespace="MyExtensionNamespace.MyExtensionClassName" %>
How do I do the same with MVC so my extension method for my Html Helper will resolve correctly and my method will show up in IntelliSense?
To be clear, I am only trying to add extensions to existing methods so that they will accept different arguments as parameters, such as System.Reflection.PropertyInfo
For example, I want to an an extension method for System.Reflection.PropertyInfo
to @Html.Label
@{
System.Reflection.PropertyInfo[] props = typeof(MyClaimDto).GetProperties();
foreach (var prop in props)
{
if (prop.PropertyType != typeof(MyNamespace.DynamicDictionary))
{
<div class="form-group">
@Html.LabelFor(prop, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Editor(prop.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.Hidden("Utility." + prop.PropertyType.FullName, new { @class = "form-control" } )
@Html.Hidden("PlaceHolder." + prop.Name, new { @class = "form-control" } )
@Html.ValidationMessage(prop.Name, "", new { @class = "text-danger" })
</div>
</div>
}
}
}
But VS tells me I still have an error under my call that says the Type Arguments could not be inferred:
Here's the code for my extension:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.Linq.Expressions;
namespace EFWCF.Extensions
{
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<PropertyInfo, TValue>(this HtmlHelper<PropertyInfo> html, Expression<Func<PropertyInfo, TValue>> expression)
{
var type = expression.Type;
MvcHtmlString result = new MvcHtmlString(type.FullName);
return result;
}
}
}
If I give the method a different name it will resolve:
public static MvcHtmlString PropertyLabelFor<PropertyInfo, TValue>(this HtmlHelper<PropertyInfo> html)
{
var type = expression.Type;
MvcHtmlString result = new MvcHtmlString(type.FullName);
return result;
}
And:
@Html.PropertyLabelFor(prop)
But I want to be able to call existing @Html methods for additional types.