Developer Forum »
Webnodes model binding (MVC-tip)
42 posts

Quite often I find myself having a controller with an id parameter that references some node in Webnodes. I would then have to query that node id in order to manipulate it. E.g.:

public ActionResult(int id) { var article = WAFContext.Session.GetContent<Article>(id); ... }

It's possible to bind all Webnodes content types to instead achieve something like this:

public ActionResult(Article article) { ... }

 

To do this you need to create 2 classes and add a line to Application_Start():

 

public class ContentBaseModelBinder : IModelBinder

{

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

{

return WAFContext.Session.GetContent(int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue, CultureInfo.InvariantCulture));

}

}

 

public class InheritanceAwareModelBinderProvider : Dictionary<Type, IModelBinder>, IModelBinderProvider

{

public IModelBinder GetBinder(Type modelType)

{

return this.Where(b => b.Key.IsAssignableFrom(modelType)).Select(b => b.Value).FirstOrDefault();

}

}

 

In Application_Start():

ModelBinderProviders.BinderProviders.Add(new InheritanceAwareModelBinderProvider { { typeof(ContentBase), new ContentBaseModelBinder() } });

181 posts

Thanks for the great tip, Emil!

1