ASP.Net MVC自訂Json轉換的ModelBinder
ASP.Net MVC其實本身有自己內建的ModelBinder,在實際應用上預設的ModelBinder我認可以處理80%的狀況,但是剩餘的20%的狀況就必需要自訂一個ModelBinder了。
手邊這個需求是使用Ajax Post資料到伺服器這邊來,由於資料傳輸格式上大家目前比較偏好採用JSON的格式,因此,有不少第三方的Js套件幾乎都有提供”toJSON”這個API讓你使用,但是伺服器端的ModelBinder本質上是看不太懂JSON資料的,因此,常常在實做中會發現到該輸入參數的值是null。
為了解決讓前後端都方便的問題,這個時候就必需要採用自定義的ModelBinder了;並且該自定義的ModelBinder是針對JSON格式的資料進行處理,其程式碼內容如下:
{
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext ctx, ModelBindingContext bCtx)
{
var stringified = ctx.HttpContext.Request[bCtx.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
var model = JsonConvert.DeserializeObject(stringified, bCtx.ModelType);
return model;
}
}
}這段程式碼是參考某個論壇Q&A所來的,但是來源我已經忘掉了… ![]()
(若有大大發現,麻煩通知我讓我補上Url)
而在Controller中,我們套用這個自定義的ModelBinder方式如下:
{
...
}