3

我正在使用 ASP.NET MVC、MySQL 和 NHibernate 开发一个小站点。

我有一个联系人类:

[ModelBinder(typeof(CondicaoBinder))]
public class Contact {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }    
}

和模型粘合剂:

public class ContactBinder:IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
         Contact contact = new Contact ();
         HttpRequestBase form = controllerContext.HttpContext.Request;

         contact.Id = Int16.Parse(form["Id"]);
         contact.Name = form["Name"];
         contact.Age = Int16.Parse(form["Age"]);

         return contact;
    }
}

另外,我有一个带有表单的视图来更新我的数据库,使用这个操作:

public ActionResult Edit([ModelBinder(typeof(ContactBinder))] Contact contact) {
    contactRepo.Update(contact);

    return RedirectToAction("Index", "Contacts");
}

到这里为止,一切正常。但在更新我的联系人之前,我必须执行表单验证。

我的问题是:我应该在哪里实施此验证?在 ActionResult 方法中还是在 Model Binder 中?还是其他地方?

非常感谢。

4

3 回答 3

2

看看史蒂夫桑德森的 XVAL。

您的业​​务对象是应该应用您的业务逻辑的地方。

善良

XVal

于 2009-08-20T14:57:22.730 回答
0

我第二史蒂夫桑德森,他的书很棒。

我真的很喜欢 Rob Conery、Scott Hanselman、Phil Haack、Scott Guthrie 所写的书呆子晚餐方法。基本上,您在每个实体中都有一个针对业务逻辑进行验证的方法。该方法返回包含字段/错误消息的 RuleViolations 列表。为了方便起见,您还公开了一个布尔值。

您可以在这里获得免费章节:书呆子晚餐章节

于 2009-08-20T15:03:40.723 回答
0

我认为这种情况下最好遵循 Microsoft 的建议,即使用服务层进行验证

于 2009-08-20T15:03:48.070 回答