Ric*_*ews 6 model-binding nancy
你能在Nancy有多个自定义模型绑定器吗?我需要绑定来自datatables jQuery插件的服务器端处理请求,这不适合我们当前的"mvc样式"自定义模型绑定器.特别是关于列表,数据表将它们表示为mylist_0,mylist_1等而不是mylist [0],mylist [1].
那么我可以添加另一个模型绑定器来处理这些不同的列表样式,如果我这样做,南希怎么知道使用哪一个?
Chr*_*man 11
您可以将自定义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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2709 次 |
| 最近记录: |