废话不多说了,说多了浪费时间,直接来代码:
public class JsonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string json = string.Empty;
var provider = bindingContext.ValueProvider;
var providerValue = provider.GetValue(bindingContext.ModelName);
if (providerValue != null)
json = providerValue.AttemptedValue;
if (Regex.IsMatch(json, @"^(\[.*\]|{.*})$"))
{
return new JavaScriptSerializer().Deserialize(json, bindingContext.ModelType);
}
return base.BindModel(controllerContext, bindingContext);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Parameter |
AttributeTargets.Struct | AttributeTargets.Property,
AllowMultiple = false, Inherited = false)]
public class JsonModelBinderAttribute : CustomModelBinderAttribute
{
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
}
[HttpPost]
public ActionResult Index([JsonModelBinder]List<JsonAttributeStudyModel> JsonAttributeStudyModels )
{
return View();
}
$("#btnSumbit").click(function () {
var obj1 = {
Address: "北京市朝阳区",
};
var arr = new Array();
var obj = {};
obj.Id = 1;
obj.Name = "paul";
obj.Money = 112;
obj.Time = "2016-08-27";
obj.JsonAttributeCharpterStudyModel = obj1;
arr.push(obj);
$.ajax({
url: "@Url.Action("Index")",
type: "post",
dateType: "json",
contentType: "application/json",
data:JSON.stringify({ JsonAttributeStudyModels: arr }),
success: function () { },
error: function () { }
});
});
这样能直接脱离json.net等dll组件直接序列化
问题:
如果新建一个entity class:
[JsonModelBinder]
public class EntityModel
{
public IEnumerable<JsonAttributeStudyModel> JsonAttributeStudyModels { get; set; }
}
var obj1 = {
Address: "北京市朝阳区",
};
var arr = new Array();
var obj = {};
obj.Id = 1;
obj.Name = "paul";
obj.Money = 112;
obj.Time = "2016-08-27";
obj.JsonAttributeCharpterStudyModel = obj1;
arr.push(obj);
$.ajax({
url: "@Url.Action("Index")",
type: "post",
dateType: "json",
contentType: "application/json",
data: JSON.stringify({ JsonAttributeStudyModels: arr }),
success: function () { },
error: function () { }
});
[HttpPost]
public ActionResult Index(EntityModel JsonAttributeStudyModels)
{
return View();
}
既然是是attribute就应该可以在类上直接添加,但是本人试过很多种方式在action中取到的数据却始终是null ,求助览友