Len*_*rri 5 validation asp.net-mvc localization business-logic
使用Data Annotations,现在可以使用Resource.resx文件轻松本地化错误消息,例如:
public class Student
{
. . .
[Required(ErrorMessageResourceName ="Required",
ErrorMessageResourceType = typeof(StudentResources))]
[StringLength(16)]
[Display(Name = "FirstName", ResourceType = typeof(StudentResources))]
public string FirstName { get; set; }
. . .
}
Run Code Online (Sandbox Code Playgroud)
现在,假设我想检查学生是否已经在某个月和一年内付款:
public bool CheckIfAlreadyPaid(Payment payment)
{
return repository.GetPayments().Any(p => p.StudentId == payment.StudentId &&
p.Month == payment.Month &&
p.Year == payment.Year);
}
Run Code Online (Sandbox Code Playgroud)
如果他已经付款,我在服务层执行以下操作:
if (CheckIfAlreadyPaid(payment))
{
modelState.AddModelError("AlreadyPaid",
Resources.Views.Payment.PaymentCreateResources.AlreadyPaid);
}
Run Code Online (Sandbox Code Playgroud)
它可以工作,但我对在服务层内引用资源文件没有信心.
是否存在一种标准或更好的本地化错误消息的方法,这些错误消息与模型属性(数据注释)无关 - 来自业务逻辑规则的错误?我还应该将这些错误添加到ModelStateDictionary吗?
我用不同的方式做到了。该Service
层用于检查付款是否已完成。在我的示例中Controller
,我向 ModelState 对象添加一条验证错误消息,并向其传递本地化字符串资源。现在我对这种方法感觉更舒服了。
这是代码:
/// <summary>
/// Performs validation of business logic...
/// </summary>
/// <param name="payment"></param>
/// <returns></returns>
private bool ValidatePayment(Payment payment)
{
if (paymentService.IsPaymentMade(payment))
{
ModelState.AddModelError("AlreadyPaid", Localization.AlreadyPaid);
}
return ModelState.IsValid;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
为了补充我的答案,我今天刚刚发现ValidationSummary @Html.ValidationSummary(true)
正是我想要的:
Html.ValidationSummary
返回对象中验证消息的无序列表(ul 元素),ModelStateDictionary
并且可以选择仅显示模型模型级错误。
我通过了true
,它只会在页面顶部的摘要中显示模型级错误(非数据注释错误)。这很棒,但前提是它能起作用......:)
我遇到了一个问题,即当我设置ValidationSummary(true)
. 然后我用谷歌搜索并找到了这篇文章。我尝试了他的解决方案,但没有成功。然后我又进行了一些搜索,并在 Google Books 中找到了此链接(Pro ASP.NET MVC 2 Framework,作者:Steven Sanderson)。
我尝试了那里描述的传递一个空字符串作为键(string.Empty
)并且它完成了工作。
if(paymentService.IsPaymentMade(payment))
{
ModelState.AddModelError(string.Empty, Localization.PaymentAlreadyCreated);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2053 次 |
最近记录: |