从IValidatableObject.Validate返回的ValidationResult未本地化 [英] ValidationResult Returned From IValidatableObject.Validate Is Not Localized
问题描述
在我的ASP.NET MVC3站点中,我将以下内容用作视图模型:
In my ASP.NET MVC3 site, I am using the following as a View Model:
using DataResources = Namespace.For.The.Localization.Resources.IndexViewModel;
public class IndexViewModel, IValidatableObject {
private string _field1_check_value = "foo";
private string _field2_check_value = "bar";
[Required(ErrorMessageResourceName="Validation_Field1_Required", ErrorMessageResourceType=typeof(DataResources))]
[DataType(DataType.Text)]
public string Field1 { get; set; }
[Required(ErrorMessageResourceName="Validation_Field2_Required", ErrorMessageResourceType=typeof(DataResources))]
[DataType(DataType.Field2)]
public string Field2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (!(Field1.Equals(_field1_check_value) && Field2.Equals(_field2_check_value))) {
string[] memberNames = { "Field1", "Field2" };
yield return new ValidationResult(DataResources.Validation_InvalidCredentials, memberNames);
}
}
}
使用默认设置以外的其他区域查看网站时,Required
验证消息已正确定位.但是,从Validate
方法返回的消息始终处于默认区域性.
When the site is viewed using any culture other than the default, the Required
validation messages are properly localized. However, the message returned from the Validate
method are always in the default culture.
有没有办法正确定位IValidatableObject.Validate
消息?
Is there a way to properly localize the IValidatableObject.Validate
messages?
推荐答案
似乎在系统可使用区域性之前调用IValidatableObject.Validate
方法.如果Validate
方法是通过控制器操作手动调用的,则错误消息将被正确定位.
It seems that the IValidatableObject.Validate
method is called before the culture is available to the system. If the Validate
method is called manually from the controller action, the error messages are properly localized.
使用此处中列出的方法的变体,我可以通过清除ModelState并强制使用本地化的错误消息进入视图验证将在控制器操作中再次运行,如下所示:
Using a variation of the method listed here, I can get localized error messages into the view by clearing the ModelState and forcing the validation to be run again in the controller action as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IndexViewModel viewModel) {
if (ModelState.IsValid) {
//Do Stuff
return RedirectToAction("Action", "Controller");
}
else {
// The original validation did not properly localize error messages coming from IValidatableObject.Validate.
// Clearing the ModelState and forcing the validation at this point results in localized error messages.
ModelState.Clear();
var errors = viewModel.Validate(new ValidationContext(viewModel, null, null));
foreach (var error in errors)
foreach (var memberName in error.MemberNames)
ModelState.AddModelError(memberName, error.ErrorMessage);
}
return View("Index", viewModel);
}
这篇关于从IValidatableObject.Validate返回的ValidationResult未本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!