我有:
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";
> 为以下项创建值:InvalidPropertyValue
、Common_ValueNotValidForProperty
、PropertyValueInvalid
这些都不起作用。
谢谢!
更新:我也在使用非侵入式验证!
最佳答案
以下对我来说效果很好:
型号:
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/