.net - 更改、覆盖、替换、asp.net MVC 3 默认 DataAnnotations 所需值和无效值的验证消息

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

我有:

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

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

如何更改此默认消息?

我已经尝试过使用:

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

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

这些都不起作用。

谢谢!


更新:我也在使用非侵入式验证!

最佳答案

以下对我来说效果很好:

型号:

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

Controller :

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>
}
Global.asax 中的

Application_Start:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    DefaultModelBinder.ResourceClassKey = "Strings";
}

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

关于.net - 更改、覆盖、替换、asp.net MVC 3 默认 DataAnnotations 所需值和无效值的验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7808363/

相关文章:

c# - 在不同的 .NET 框架之间共享记录器

c# - Windows 应用程序已停止在客户端计算机中工作

javascript - ASP.NET MVC - 返回 JavaScriptResult 不起作用

c# - 反序列化错误

c# - 如何从数组中获取所有可能的组合?

c# - 如何以编程方式获取特定服务器标识

asp.net - 出现错误 "the element ' httpCookies' 已被锁定在更高级别的配置中”

ajax - Zend_Form ajax 查询的 csrf 验证

c# - 我应该在 DDD 域项目中验证吗?

java - 我如何自定义 EditText Box 以仅允许使用货币?