我创建了方法 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 中,如下图所示:
感谢任何帮助。
最佳答案
我最后做了这个,以防有人需要它。谢谢大家的帮助
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/