6

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?

4

2 に答える 2

12

プロジェクトにカスタムModelBinderを追加して、話しているクラスのバインディングを処理することができます。

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);
        }
    }
}
于 2012-12-06T07:59:02.157 に答える