Created
August 4, 2009 19:50
-
-
Save schourode/161479 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Or if you use binding by parameter, don't do anything at all :-) | |
public ActionResult Create(Bar bar) | |
{ | |
if (ModelState.IsValid) | |
{ | |
// Do something; | |
} | |
// Do something else; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use the TryUpdateModel() rather than UpdateModel() - the latter throws an exception when errors are detected. | |
public ActionResult Edit(FormCollection form) | |
{ | |
Foo foo = FindFoo(); | |
TryUpdateModel(foo); | |
if (ModelState.IsValid) | |
{ | |
// Do something; | |
} | |
// Do something else; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Hook up the new model binder in your application. | |
protected void Application_Start() | |
{ | |
ModelBinders.Binders.DefaultBinder = new NHibernateValidatorAwareModelBinder(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define a new type of IModelBinder, which automatically invokes NHV when binding. | |
using System.Web.Mvc; | |
public class NHibernateValidatorAwareModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
var model = base.BindModel(controllerContext, bindingContext); | |
var controller = controllerContext.Controller as Controller; | |
if (controller != null) | |
{ | |
var engine = NHibernate.Validator.Cfg.Environment.SharedEngineProvider.GetEngine(); | |
foreach (var error in engine.Validate(model)) | |
{ | |
controller.ModelState.AddModelError(error.PropertyName, error.Message); | |
} | |
} | |
return model; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment