2009-08-20 69 views
3

我正在開發一個使用ASP.NET MVC,MySQL和NHibernate的小站點。如何[和在哪裏]使用ModelBinder實現驗證

我有一個Contact類:

[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方法或在模型綁定器?還是其他地方?

非常感謝。

回答

2

看看Steve Sanderson的XVAL。

您的業務對象是您的業務邏輯應用的地方。

善良

XVal

0

我第二史蒂夫·桑德森,他的書是驚人的。

我真的很喜歡Rob Conery,Scott Hanselman,Phil Haack,Scott Guthrie寫的書呆子晚餐的方法。基本上你在每個實體中都有一個方法來驗證buisness邏輯。該方法返回包含字段/錯誤消息的RuleViolations列表。你也暴露了一個易於理解的布爾值。

你獲得免費的章節這裏:Nerd Dinner Chapter