Skip to content

Instantly share code, notes, and snippets.

@schourode
Created August 4, 2009 19:50
Show Gist options
  • Save schourode/161479 to your computer and use it in GitHub Desktop.
Save schourode/161479 to your computer and use it in GitHub Desktop.
// 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;
}
// 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;
}
// Hook up the new model binder in your application.
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new NHibernateValidatorAwareModelBinder();
}
// 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