JSON

Json传到服务端序列化json参数的Filter类

字号+ 作者:H5之家 来源:H5之家 2017-01-02 18:03 我要评论( )

在网上找了半天关于如何从前端json传过来的数据,到后台获

在网上找了半天关于如何从前端json传过来的数据,到后台获取。

主要思路如下,通过JsonParamFilter类来序列化从前端获取的数据。

JsonParamFilter.cs:

代码 using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization; // 需要引用 System.Runtime.Serialization
using System.Runtime.Serialization.Json; // 需要引用 System.ServiceModel.Web
using System.Web;
using System.Web.Mvc;


///<summary>
///使Action Method可以接收序列化后的JSON对象并转换为强类型参数
///</summary>
public class JsonParamFilter : ActionFilterAttribute
{
///<summary>
///类型名称
///</summary>
public Type TargetType { get; set; }

///<summary>
///类型对应的参数名称
///</summary>
public string Param { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
{
try
{
object o = new DataContractJsonSerializer(TargetType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;

}
catch { }
}
}
}

Action Method里的使用方法:
        [JsonParamFilter(TargetType = typeof(EmployeeInfo), Param = "employeeInfo")]
        public ActionResult TestJson(EmployeeInfo employeeInfo)
        {
            return Json(employeeInfo);
        }

客户端调用:
   <script type="text/javascript">
        var employee = new Object();
        employee.Name = "人员1";
        employee.Age = 25;
        employee.Salary = 12345;
 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Home/TestJson/",
            data: $.toJSON(employee),   // 序列化JSON对象,用了一个叫 jquery-json 的插件
            dataType: "json",
            success: function(json) {
                alert("Name:" + json.Name + ", Age:" + json.Age + ", Salary:" + json.Salary);
            }
        });
    </script>
 
  jquery-json 插件下载:jquery.json-2.2.js

  来源:博客园

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • JS将JSON对象转化为字符串的改进方法

    JS将JSON对象转化为字符串的改进方法

    2017-01-02 13:00

  • 1.2.5 在.NET中使用JSON(2)

    1.2.5 在.NET中使用JSON(2)

    2017-01-02 12:01

  • JSON进阶六-自动组装

    JSON进阶六-自动组装

    2017-01-02 08:00

  • PHP 5.4不对中文json编码的方法

    PHP 5.4不对中文json编码的方法

    2017-01-01 18:05

网友点评