c# - 从代码访问 View 模型所需的错误消息数据注释属性 - MVC、Razor

标签 c# .net asp.net-mvc razor model-view-controller

我创建了方法 ExtendedTextBoxFor,我想访问我作为参数发送的属性的 View 模型消息。我可以毫无问题地访问 IsRequired 属性,但错误消息似乎是非公共(public)属性,有什么方法可以访问它吗?

到目前为止我有这个:

public static MvcHtmlString ExtendedTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        if (metadata.IsRequired)
        {
            //Read error message from ViewModel
        }

        return InputExtensions.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (string)null, htmlAttributes);
    }

错误消息在元数据> PrototypeCache > Required > ErrorMessage 中,如下图所示:

Wanted value

感谢任何帮助。

最佳答案

我最后做了这个,以防有人需要它。谢谢大家的帮助

private static string GetErrorMessage(ModelMetadata metadata)
    {
        string retVal = String.Empty;

        var customTypeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(metadata.ContainerType).GetTypeDescriptor(metadata.ContainerType);
        if (customTypeDescriptor != null)
        {
            var descriptor = customTypeDescriptor.GetProperties().Find(metadata.PropertyName, true);
            var req = (new List<Attribute>(descriptor.Attributes.OfType<Attribute>())).OfType<RequiredAttribute>().FirstOrDefault();

            if (req != null)
                retVal = req.ErrorMessage;
        }

        return retVal;
    }

关于c# - 从代码访问 View 模型所需的错误消息数据注释属性 - MVC、Razor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761891/

相关文章:

ASP.NET Windows 身份验证路由不同组

c# - 跨多林环境从域本地组获取所有成员

c# - 获取转义的多语法 sql 更新字符串

c# - 无法使用 migrate.exe 运行代码优先迁移

c# - 加密字符串时重用 AES 对象是否安全?

asp.net-mvc - ASP.NET MVC : Route with optional parameter,,但如果提供,则必须匹配\d+

c# - 用C#向mySQL插入点符号错误

c# - 在数据库中存储连接字符串

.net - 在遇到问题的 Docker 上部署 Blazor Client(WebAssembly)

c# - 在 View 中渲染包含 Razor 代码的字符串