我正在尝试注册自定义 MVC HtmlHelper 扩展。
我已经为我的扩展方法创建了适当的静态类和静态方法,但是如何在我的 View 中注册/导入/使用该命名空间,以便它显示为某些给定方法的扩展方法,对于 @Html .SomeMethod
在 Asp.Net WebForms 中我可以简单地添加:
<%@ Import Namespace="MyExtensionNamespace.MyExtensionClassName" %>
如何对 MVC 执行相同操作,以便我的 Html Helper 扩展方法能够正确解析,并且我的方法将显示在 IntelliSense 中?
需要明确的是,我只是尝试向现有方法添加扩展,以便它们接受不同的参数作为参数,例如 System.Reflection.PropertyInfo
例如,我想要将 System.Reflection.PropertyInfo
的扩展方法扩展为 @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>
}
}
}
但是 VS 告诉我,我的调用下仍然出现错误,提示无法推断类型参数:
这是我的扩展的代码:
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;
}
}
}
如果我给该方法一个不同的名称,它将解析:
public static MvcHtmlString PropertyLabelFor<PropertyInfo, TValue>(this HtmlHelper<PropertyInfo> html)
{
var type = expression.Type;
MvcHtmlString result = new MvcHtmlString(type.FullName);
return result;
}
还有:
@Html.PropertyLabelFor(prop)
但我希望能够为其他类型调用现有的 @Html 方法。
最佳答案
您可以通过以下两种方式引用命名空间:
直接在 View 中:
@using YourProject.HtmlHelpers;
或者您可以在 Views/web.config
文件中添加对该命名空间的引用,这样就无需将 using
添加到 View 顶部:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- Reference here -->
<add namespace="YourProject.HtmlHelpers" />
</namespaces>
</pages>
</system.web.webPages.razor>
关于c# - 如何重载 MVC HtmlHelper 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002598/