2012-12-05 33 views
5

南希能有多個自定義模型活頁夾嗎?我需要綁定來自datatables jQuery插件的服務器端處理請求,它不適合我們當前的「mvc風格」自定義模型聯編程序。特別是關於列表,數據表將它們表示爲mylist_0,mylist_1等,而不是mylist [0],mylist [1]。南希的多個自定義模型活頁夾

所以我可以添加另一個模型聯編程序來處理這些不同的列表樣式,如果我確實知道Nancy如何知道使用哪一個?

回答

10

您可以將自定義的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); 
     } 
    } 
} 
+3

應該框架自動檢測您的自定義粘結劑,或是否需要在某處註冊? (Nancy的文檔對此很渺茫。) – 2014-06-28 22:16:23

0

如果CustomModelBinder未檢測到(因爲它發生在我身上),你可以嘗試在CustomBootstrapper覆蓋它:

protected override IEnumerable<Type> ModelBinders 
    { 
     get 
     { 
      return new[] { typeof(Binding.CustomModelBinder) }; 
     } 
    }