Asp.net mvc MVC3客户端验证-仅显示“*“必需”;
是否有一种快速的方法来默认模型中所有字段的错误消息 我希望验证返回以下文本: “*必需” …但不希望在每个字段上手动设置Asp.net mvc MVC3客户端验证-仅显示“*“必需”;,asp.net-mvc,asp.net-mvc-3,data-annotations,Asp.net Mvc,Asp.net Mvc 3,Data Annotations,是否有一种快速的方法来默认模型中所有字段的错误消息 我希望验证返回以下文本: “*必需” …但不希望在每个字段上手动设置 谢谢Paul您可以编写自定义的必需属性 [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] public sealed c
谢谢Paul您可以编写自定义的必需属性
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AEMRequiredAttribute: ValidationAttribute
{
private const string _defaultErrorMessage = "* required";
public AEMRequiredAttribute()
: base(_defaultErrorMessage)
{ }
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, "* required", name);
}
public override bool IsValid(object value)
{
if (value == null || String.IsNullOrWhiteSpace(value.ToString())) return false;
else return true;
}
}
按如下方式调用此属性:
public partial class AEMClass
{
[DisplayName("Dis1")]
[AEMRequiredAttribute]
public string ContractNo { get; set; }
}
您可以创建一个新的HTML帮助程序,然后调用底层的
ValidationMessage
或ValidationMessageFor
帮助程序来设置消息文本
基于ValidationMessageFor
的内容如下所示:
public static class HtmlHelperExtensions {
public static IHtmlString ValidatorMessageWithMyTextFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {
return htmlHelper.ValidationMessageFor<TModel, TProperty>(expression, "required *");
}
}
当然,这一切都是从应用程序的视图端而不是模型端工作的,所以这一切都取决于您希望将消息嵌入到哪里。如果是模型方面,那么AEM的解决方案是好的。好问题…+1。看我的帖子。
@Html.ValidatorMessageWithMyTextFor(m=>m.MyModelPropertyToValidate)