【问题标题】:Is it possible to set the default validation message to "This field is required" for Html.DropDownListFor?是否可以将 Html.DropDownListFor 的默认验证消息设置为“此字段是必需的”?
【发布时间】:2018-04-13 01:29:11
【问题描述】:

我们继承了一个应用程序,并有一个关于使用@Html.DropDownListFor 的查询

@Html.DropDownListFor(model => model.SomeLookup.Id
, new SelectList(SomeList, "Id", "Description")
, "-- select --")

data-val-required 属性在渲染控件上默认设置为

data-val-required="The Id field is required."

这会覆盖任何验证脚本。

我们知道我们可以将 data_val_required 属性设置为我们想要的消息,如下所示:

@Html.DropDownListFor(model => model.SomeLookup.Id
, new SelectList(SomeList, "Id", "Description")
, "-- select --"
, new [] { data_val_required="This field is required" })

问题是我们需要设置属性的应用程序(可能还有其他应用程序)的多个页面中有几十个下拉菜单。如果我们忘记这样做,用户会收到他们感到困惑的默认消息。

是否可以覆盖此默认值,以便无论在何处使用它,使用的默认消息都是“此字段是必需的”?

【问题讨论】:

  • 参考this answer - 如果您不想添加自己的[Required(ErrorMessage = "...")] 属性,则需要创建一个资源文件来覆盖默认值
  • 附带说明,SelectList 构造函数中的 default(int) 参数毫无意义 - 它被忽略 - 所选选项是根据您的 Id 属性的值设置的
  • “作为旁注,您的默认值(int)...”。我已经更新了示例,所以这不再是一种干扰。
  • 只需删除第四个参数 - 它毫无意义:)
  • 完成 :) 很高兴知道!我已将资源文件 Resources.resx 文件添加到新创建的 App_GlobalResources 文件夹中,并添加了 DefaultModelBinder.ResourceClassKey = "Resources";在 Global.asax Application_Start() 方法中。但不确定属性名称需要是什么,尝试了 DefaultModelBinder_ValueRequired、PropertyValueRequired 甚至 data_val_required。会继续打猎,但如果你知道了,那会很方便。

标签: asp.net-mvc html.dropdownlistfor


【解决方案1】:

默认消息在System.ComponentModel.DataAnnotations 资源文件中定义。要覆盖它,您可以通过从 RequiredAttributeAdapter 继承来创建自定义 DataAnnotationsModelValidator

首先在App_GlobalResources 中创建一个资源文件,比如MyResources.resx,然后添加以下键/值(确保访问修饰符为public

PropertyValueRequired This field is required

然后创建以下适配器

public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(App_GlobalResources.MyResources);
        attribute.ErrorMessageResourceName = "PropertyValueRequired";
    }
}

最后在Global.asax.cs注册适配器

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RequiredAttribute), typeof(MyRequiredAttributeAdapter));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2014-10-15
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多