Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple custom model binders in Nancy

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?

like image 358
Rich Andrews Avatar asked Dec 05 '12 18:12

Rich Andrews


2 Answers

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);
        }
    }
}
like image 72
Christian Westman Avatar answered Oct 02 '22 13:10

Christian Westman


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) };
        }
    }
like image 44
Evaldas Miliauskas Avatar answered Oct 02 '22 12:10

Evaldas Miliauskas