zoukankan      html  css  js  c++  java
  • 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;

    }
    }

  • 相关阅读:
    Springboot(一)springboot简介与入门程序
    Java基础(二)流程语句与数组
    Java基础(一)基础常识
    Kubernetes介绍
    K8s 存储
    Kubernetes 集群组件
    Kubernetes 设计理念
    Kubernetes 部署与实战
    容器技术与资源隔离
    Docker 网络配置
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/5557369.html
Copyright © 2011-2022 走看看