【问题标题】:Change, override, replace, asp.net MVC 3 default DataAnnotations Validations messages for required and invalid values更改、覆盖、替换、asp.net MVC 3 默认 DataAnnotations 验证消息,用于必需和无效值
【发布时间】:2011-10-18 13:55:53
【问题描述】:

我有:

public class StudentDto
{
    [Display(Name = "Data de Nascimento")]
    public DateTime? Born { get; set; }
}

我正在使用 jQuery datepicker,每当我输入无效数据时,验证消息是:请输入有效日期。

如何更改此默认消息?

我已经尝试过使用:

[DataType(DataType.Date, ErrorMessage = @"Valor inválido")]

我已经尝试创建.resx,并使用DefaultModelBinder.ResourceClassKey = "Strings";,并在我的.resx 上为:InvalidPropertyValueCommon_ValueNotValidForPropertyPropertyValueInvalid 创建值

这些都不起作用。

谢谢!


更新:我也在使用不显眼的验证!

【问题讨论】:

    标签: .net asp.net-mvc-3 validation data-annotations


    【解决方案1】:

    以下对我来说很好用:

    型号:

    public class StudentDto
    {
        [Display(Name = "Data de Nascimento")]
        [Required(ErrorMessage = "Some custom message for required date")]  
        public DateTime? Born { get; set; }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new StudentDto());
        }
    
        [HttpPost]
        public ActionResult Index(StudentDto dto)
        {
            return View(dto);
        }
    }
    

    查看:

    <script type="text/javascript">
        $(function () {
            $('#Born').datepicker();
        });
    </script>
    
    @using (Html.BeginForm())
    {
        @Html.LabelFor(x => x.Born)
        @Html.EditorFor(x => x.Born)
        @Html.ValidationMessageFor(x => x.Born)
        <button type="submit">OK</button>
    }
    

    Application_Start 在 Global.asax:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    
        DefaultModelBinder.ResourceClassKey = "Strings";
    }
    

    ~/App_GlobalResources/Strings.resx 中定义键PropertyValueInvalid,如果输入的日期无效,将使用该键。对于值,您可以使用 {0}{1} 占位符,它们将分别替换为字段的值和显示名称。

    【讨论】:

    • 我无法理解...所需的消息工作正常,但无效数据不能!我做了和你说的一模一样的事=/
    • @Renanlf,我从头开始创建了一个新的 ASP.NET MVC 3 项目,并将您在我的答案中看到的代码放在正确的位置。我刚刚在 _Layout 中引用了 jquery-ui.js 以使日期选择器正常工作。那么,如果它对你不起作用,你和我有什么不同呢?要我给你发一份我的项目的工作副本吗?
    • 也许我的问题出在不显眼的 ajax 上!您的代码是否可以在不显眼的情况下使用??
    • @Renanlf,不引人注目的是什么?验证?阿贾克斯?
    • 是的! 和 jquery.validate.unobtrusive.min.js
    【解决方案2】:

    使用 DefaultModelBinder.ResourceClassKey = "Strings"; 进行绑定验证 (forums.asp.net/post/3607981.aspx) 和 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Strings"; 进行不显眼的验证。

    Strings - 位于App_GlobalResources 文件夹 (~/App_GlobalResources/Strings.resx) 中的资源文件的名称。

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 1970-01-01
      • 2014-11-13
      • 2014-04-04
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多