Can you have multiple custom model binders in Nancy? I need to bind the server side processing request from datatables jQuery plugin which doesn't fit with our current "mvc style" custom model binder. Specifically regarding lists, datatables presents them as mylist_0, mylist_1 etc instead of mylist [0], mylist [1].
So can I add another model binder to handle these differing list styles and if I do how does Nancy know which one to use?
You could add a custom ModelBinder to your project to handle the binding of the class you are talking about.
using System;
using System.IO;
using Nancy;
namespace WebApplication3
{
public class CustomModelBinder : Nancy.ModelBinding.IModelBinder
{
public object Bind(NancyContext context, Type modelType, object instance = null, params string[] blackList)
{
using (var sr = new StreamReader(context.Request.Body))
{
var json = sr.ReadToEnd();
// you now you have the raw json from the request body
// you can simply deserialize it below or do some custom deserialization
if (!json.Contains("mylist_"))
{
var myAwesomeListObject = new Nancy.Json.JavaScriptSerializer().Deserialize<MyAwesomeListObject>(json);
return myAwesomeListObject;
}
else
{
return DoSomeFunkyStuffAndReturnMyAwesomeListObject(json);
}
}
}
public MyAwesomeListObject DoSomeFunkyStuffAndReturnMyAwesomeListObject(string json)
{
// your implementation here or something
}
public bool CanBind(Type modelType)
{
return modelType == typeof(MyAwesomeListObject);
}
}
}
In case CustomModelBinder
is not detected (as it happens to me), you can try overriding it in CustomBootstrapper
:
protected override IEnumerable<Type> ModelBinders
{
get
{
return new[] { typeof(Binding.CustomModelBinder) };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With