C# 在静态上下文中访问 IModelMetaDataProvider - IHtmlHelper

标签 c# .net asp.net-core

我正在探索实现可与我的 Razor View 一起使用的自定义复选框助手的方法。该应用程序正在使用 Microsoft.AspNetCore 2.0.0 .您已经尝试过自定义 TagHelper IHtmlHelper 的解决方案和静态扩展方法.

不幸的是,该项目最初是 MVC5 有大量需要移植的遗留 MVC5 静态助手。

有问题的方法调用是 arg[2] 在这里:

    ModelExplorer metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, (ViewDataDictionary<TModel>)html.ViewData, [I need to resolve and pass in IModelMetadataProvider here]);

这是帮助程序的基本代码

    public static IHtmlContent MvcCheckBoxFor<TModel, TResult>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TResult>> expression, object htmlAttributes = null)
    {

        // see http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/Html/InputExtensions.cs this applies the correct "name" HTMl attribute

        if (expression == null)
        {
            throw new ArgumentNullException("expression");
        }


        // TODO: Resolve IModelMetedataProvider - argument 3 - left null 
        ModelExplorer metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, (ViewDataDictionary<TModel>)html.ViewData, null);


        bool isChecked = false;
        if (metadata.Model != null)
        {
            bool modelChecked;
            if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))
            {
                isChecked = modelChecked;
            }
        }

        string fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

        return CheckBoxHelper(fullName, fullName, isChecked, htmlAttributes);
    }

我省略了 CheckBoxHelper代码,因为功能不在问题范围之内。虽然签名如下:

 private static IHtmlContent CheckBoxHelper(string name, string id, bool isChecked, object htmlAttributes)

实现调用 .NET 4.5.2 的旧方法是:

 ModelMetadata.FromLambdaExpression(expression, html.ViewData);

签名和命名空间从 System.Web.Mvc 更改至 Microsoft.AspNetCore.Mvc.ViewFeatures.Internal

只是想知道我可以使用什么策略来进行此调用。 MSFT 的助手,例如 @Html.LabelFor必须在幕后做一些事情——它们也在静态环境中。

Activator.CreateInstance<IModelMetadataProvider>()可用但不可行,因为您无法创建接口(interface)的实例。有具体的类型或解决方法吗?

任何帮助将不胜感激。

非常感谢您花时间阅读本文,

约翰

最佳答案

刚刚查看了 IHtmlHelper 代码 - 有一个 IModelMetadataProvider 只读字段。

所以,

html.MetadataProvider

解决它。我觉得很傻。非常感谢 MSFT 将其包括在内!

关于C# 在静态上下文中访问 IModelMetaDataProvider - IHtmlHelper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501943/

相关文章:

c# - 在 View 中创建 ViewModel 的实例可以吗?

c# - 将图像保存到本地路径时发生错误

c# - MTOM - 在 VS 2010 中读取时遇到无效的 MIME 内容类型 header

c# - .Net 枚举 winforms 字体样式?

c# - 无法加载文件或程序集“System.Security.Cryptography.Algorithms,版本 = 4.1.0.0

asp.net-core - .NET Core 1.0.0 RC2 中 OpenIdConnectOptions 中的通知在哪里?

c# - 扩展 Entity Framework 将列添加到 Identity Server 4 客户端表

c# - 如何使用 C# 将转义字符放在特殊字符之前?

c# - 优化 ASP.NET Core 发布包

azure - 在 Azure Application Insights 中查看错误响应文本