ajax modelbinder,Mvc用DefaultModelBinder处理Json序列化数据

本文介绍了如何在ASP.NET MVC中创建一个自定义的JsonModelBinder,以便在不依赖json.net等DLL组件的情况下直接进行JSON序列化。通过`JsonModelBinder`类和`JsonModelBinderAttribute`特性,实现了模型绑定从JSON到C#对象的转换。示例代码展示了一个使用Ajax提交JSON数据到控制器Action的方法,并讨论了在Action中获取数据为null的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说了,说多了浪费时间,直接来代码:

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 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 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  ,求助览友

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值