Ajax Post 类实例

以前总是ajax请求是这样的

data:"a=1&b=2&c=3..."

而Controller也总是这样的

Action(int a,int b,int c)

很丑!!!

现在可以这样了

<!doctype html>
<html>
<head>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
$(function () {

$('#getMsg').click(
function () {
var msg = {};
var msgs=[];
msg.Data = "";
msg.ErrorCode = 1;
msg.ErrorMsg = "不合法的数据类型";
msgs.push(msg);

$.ajax({
url: '/Home/GetMessage',
data: {
msg: JSON.stringify(msg),
msgList: JSON.stringify(msgs)
},
datatype: "json",
type: "post",
contenttype: "application/json",
success: function (result) {
alert(result.Message);
},
error: function (result) {
alert("操作失败!");
}
});
});
});
</script>
</head>
<body>
<button id="getMsg">SendMsg </button>
</body>
</html>

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

public ActionResult GetMessage( [ModelBinder(typeof(JsonBinder<CMessage>))]CMessage msg,
[ModelBinder(typeof(JsonBinder<List<CMessage>>))]List<CMessage> msgList
)
{

return View();
}

public class JsonBinder<T> : IModelBinder where T:class
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//从请求中获取提交的参数数据
var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;

//如果获取不到数据直接返回空
if (json == null)
{
return null;
}
return json.ToInstance<T>();

}
}
public static class JsonHelper
{
public static String ToJson<T>(this T ojb) where T : class
{
return JsonConvert.SerializeObject(ojb, Formatting.Indented);

}
public static T ToInstance<T>(this String jsonStr) where T : class
{
var instance = JsonConvert.DeserializeObject<T>(jsonStr);

return instance;

}
}

上一篇:初学c# -- 学习笔记(八)


下一篇:ASP.NET Core 使用 Hangfire 定时任务