【发布时间】:2011-02-03 20:53:17
【问题描述】:
我正在使用带有 ModelStateWrapper 的服务层,如 here 所示。
在服务层中验证时控制错误键的正确方法是什么,以便它们与我的视图中的输入名称相对应?
例如我为客户提供以下 ViewModel:
public class CustomerViewModel
{
public string Name { get; set; }
/*…*/
}
下面是一些用例视图的视图模型(用户可以通过输入他们的名字在这个用例中动态创建两个客户):
public class SomeOtherUseCaseViewModel
{
public CustomerViewModel BuyingCustomer { get; set; }
public CustomerViewModel SellingCustomer { get; set; }
/*… */
}
我在视图中这样使用:
<!-- … -->
<%: Html.EditorFor(model => model.BuyingCustomer.Name) %>
<%: Html.ValidationMessageFor(model => model.BuyingCustomer.Name) %>
<!-- … -->
<%: Html.EditorFor(model => model.SellingCustomer.Name) %>
<%: Html.ValidationMessageFor(model => model.SellingCustomer.Name) %>
在我的客户服务中,我有以下在创建客户时调用的验证方法(请注意,这是一个不同的客户类,这是一个域类):
public bool ValidateCustomer(Customer customer)
{
/* Check if there is another customer with the same name */
if (/*…*/)
{
_validationDictionary.addError(“Name”, “There is another customer with the same name”); //the _validationDictionary holds the ModelStateWrapper
return false;
}
}
你看到我的问题了吗?
根据视图,错误应该添加键“BuyingCustomer.Name”或“SellingCustomer.Name”(或者最终会出现两个错误,每个键一个),而不仅仅是“名称”;否则框架将无法正确突出显示字段并显示错误。
什么是巧妙解决这种情况的正确方法?我不想将“错误键前缀”传递给服务层,因为这是 UI 问题而不是服务层问题,(对吧?)。
【问题讨论】:
标签: asp.net-mvc modelstate service-layer