[英]MVC3 modifying model validation metadata and error messages
我需要ASP.NET MVC3模型验证逻辑的解决方案。 我有一个自定义的本地化解决方案,我正在通过一种翻译方法传递所有字符串,例如:
@Localizer.Translate("Hello world!")
注意:我不确定,但是我认为这种方法来自QT本地化逻辑。 WordPress也使用smillar技术。
当我尝试将此解决方案用于模型验证属性时:
[Required(ErrorMessage = Localizer.Translate( "Please enter detail text!"))]
[DisplayName(Localizer.Translate( "Detail"))]
public string Details { get; set; }
编译器给我这个错误:
错误1属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式...
因此,我试图即时修改错误消息和DisplayName属性,但我做不到。
有没有办法做到这一点? 如果有的话,可能对我来说是救命的方法:)
您可以使用资源文件进行本地化 。
将资源文件(您可以通过Visual Studio使用“添加新项”向导-称为MyResourcesType.resx)添加到项目中。 然后添加您的验证消息,如下所示:
[Required(
ErrorMessageResourceType = typeof(MyResourcesType),
ErrorMessageResourceName = "MyMessageIdOnTheResourcesFile")]
从现在开始,更改语言只是添加新资源文件的问题。 检查此问题的第一个答案 。
顺便说一下,不要使用DisplayNameAttribute,而是使用System.ComponentModel.DataAnnotations命名空间中的DisplayAttribute 。 这是MVC使用的属性,您也可以对其进行本地化:
[Display(
ResourceType = typeof(MyResourcesType),
Name = "MyPropertyIdOnResourcesFile_Name",
ShortName = "MyPropertyIdOnResourcesFile_ShortName",
Description = "MyPropertyIdOnResourcesFile_Description")]
属性的工作方式是将它们静态地编译到代码中。 因此,您不能拥有使用属性时那样的任何动态功能。
Jota的答案是推荐的处理方式,但是,如果您决定使用自己的解决方案,则可以创建自己的属性,并可以在该属性中添加用于查找消息的代码。
我有一种解决方法,可以创建我的自定义@ Html.LabelFor()和@ html.DescriptionFor()帮助器。
我的助手:
namespace MyCMS.Helpers
{
public static class Html
{
public static MvcHtmlString DescriptionFor<TModel, TValue>(
this HtmlHelper<TModel> self,
Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
var description = Localizer.Translate(metadata.Description);
return MvcHtmlString.Create(string.Format(@"<span class=""help-block"">{0}</span>", description));
}
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> self,
Expression<Func<TModel, TValue>> expression,
bool showToolTip
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
var name = Localizer.Translate(metadata.DisplayName);
return MvcHtmlString.Create(string.Format(@"<label for=""{0}"">{1}</label>", metadata.PropertyName, name));
}
}
}
我的看法是:
@使用MyCMS.Localization; @使用MyCMS.Helpers;
<div class="clearfix ">
@Html.LabelFor(model => model.RecordDetails.TitleAlternative)
<div class="input">
@Html.TextBoxFor(model => model.RecordDetails.TitleAlternative, new { @class = "xxlarge" })
@Html.ValidationMessageFor(model => model.RecordDetails.TitleAlternative)
@Html.DescriptionFor(model => model.RecordDetails.TitleAlternative)
</div>
</div>
我可以使用我的本地化方法:)
再次感谢大家...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.