从代码中的资源文件访问视图模型所需的错误消息数据注释 - MVC

时间:2015-09-30 08:27:16

标签: c# asp.net-mvc

我试图从代码中访问ErrorMessageString以获取基于用户语言的相应消息,但是我遇到了一些困难。

在我的viewModel中我有这个:

    [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "UserFirstNameReq")]
    [Display(Name = "UserFirstName", ResourceType = typeof(Resource))]
    public string FirstName { get; set; }

来自英语资源文件UserFirstNameReq =名字是必需的。 (这将根据用户语言选择而改变,对于德语,这将是Vorname ist erforderlich。)

现在我有了这段代码,我想访问已翻译的消息,但无法访问ErrorMessageString。我怎样才能得到这个值?

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 input is required in ViewModel, attach required and validation message
        if (metadata.IsRequired)
        {
            string errorAtribute = GetErrorMessage(metadata);

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

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

    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;

                //Here instead of ErrorMessage i need ErrorMessageString
            }

        }

        return retVal;
     }

以下是我需要但无法访问的屏幕截图:

enter image description here

感谢任何帮助。谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

如果使用反射不是问题,请尝试

retVal =  (string)req.GetType().GetProperty("ErrorMessageString", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(req);