.NET MVC3 几种返回 JSON 对象的方式和注意事项

.NET MVC3 几种返回 JSON 对象的方式和注意事项

引言
 在用 .NET MVC3 给我们做 WEB 项目带来很大灵活性同时,
对刚上手的同学来说有些细微的设置导致的问题让我们
相当的“纠结”!

这里要讨论的就是:使用JQuery的 Ajax 请求后“返回”的
JSON 数据问题。

 相信大多数同学都会遇到过,就是在后台已经拼接好了一
(拼接方法比较多,我的博客也有提到过!)
串标准的JSON字符串,但是 Ajax 的 success 方法就是
无法正常解析 JSON 对象(相当郁闷啊!如果不是前端
高手非得调疯了!)。

下面将解几种返回 JSON 的方法和注意事项!

注:我们默认前端使用的是 JQuery的 Ajax 请求.格式如下
当然我要返回的JSON 是下面形式的

1.前台脚本
/*
 {
   Data:true,
  Msg:"成功",
  Result:true
  }
*/
//JQuery的 Ajax 请求
  $.ajax({
    type: "Post",
    url: "AddUser.aspx",
    data: "",
    dataType: "json", //如果要返回 json 这里很重要哦!!详细说明参见JQuery的API手册吧
    success: function (result) {
    alert(result.Result);
      if (result.Result) {
        alert('成功');
      }
      else {
        alert("失败");
      }
    },
    complete: function (XMLHttpRequest, textStatus) {
      //alert("complete");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("error");
      // alert(XMLHttpRequest);
      // alert(errorThrown);
      // alert(textStatus);
    }
  });
}

2.后台代码

定义1:
返回的都是 ResultInfo 对象,对象声明如下

  /// <summary>
  /// 调用结果信息类
  /// </summary>
  /// <typeparam name="T">泛型类型</typeparam>
  public class ResultInfo<T> where T:new ()
  {
    /// <summary>
    /// 调用结果是否成功
    /// </summary>
    public bool Result { set; get; }
    /// <summary>
    /// 调用结果返回的数据
    /// </summary>
    public T Data { set; get; }
    /// <summary>
    /// 调用结果返回的相关提示信息
    /// </summary>
    public string Msg { set; get; }
  }

定义2:
 ToJsonStr() 方法,是我自己封装的一个将对象转换为 Json
字符串的一个扩展方法。

2.1 请求的返回值为 JsonResult 对象

    public JsonResult AddUser()
    {
      bool flag = true;
      ResultInfo<bool> result = new ResultInfo<bool>()
      {
        Result = flag,
        Msg = flag ? "成功" : "失败",
        Data = flag
      };
      JsonResult js = new JsonResult();
      js.Data = result;
      return js;
    }

说明:
 JsonResult 对象比较方便了用着,你只需要将对象赋值
给它的实例化对象的 Data 属性,之后直接返回它就OK了,其他
的如何将对象转为 Json 字符串你都不用考录了!
 但要注意的是:如果你画蛇添足,把对象转为 Json 字符串,然后
再赋值给 Data 属性,客户端是得不到 Json 对象的!

2.2 请求的返回值为 ActionResult 对象

    public ActionResult AddUser()
    {
      bool flag = true;
      ResultInfo<bool> result = new ResultInfo<bool>()
      {
        Result = flag,
        Msg = flag ? "成功" : "失败",
        Data = flag
      };
      string json = result.ToJsonStr();

      return Content(json);

      //return Content(json,"text/json"); //这种写法也可以,第二个参数就是:MIME类型

    }

说明:
 当然你也可以使用 2.1 中的方式,返回 JsonResult 对象,咱们现在
要用另外一种方式返回JSON。
 用这种方式脚本那边儿需要提供支持!就是要保证 JQuery的 Ajax 请求
的 dataType 属性值必须设为 "json",即:dataType: "json"。
  没有这个支持你得到的将会是一个字符串!

2.3 请求的返回值为 string 对象

    public string AddUser()
    {
      bool flag = true;
      ResultInfo<bool> result = new ResultInfo<bool>()
      {
        Result = flag,
        Msg = flag ? "成功" : "失败",
        Data = flag
      };
      string json = result.ToJsonStr();
      return json;
    }

说明:
 用这种方式脚本那边儿需要提供支持!就是要保证 JQuery的 Ajax 请求
的 dataType 属性值必须设为 "json",即:dataType: "json"。
  没有这个支持你得到的将会是一个字符串!

2.4 设置 Response.ContentType 属性

   public string AddUser()
   {
      bool flag = true;
      ResultInfo<bool> result = new ResultInfo<bool>()
      {
        Result = flag,
        Msg = flag ? "成功" : "失败",
        Data = flag
      };
      Response.ContentType = "application/json; charset=utf-8";
      string json = result.ToJsonStr();
      return json;
    }

说明:
 如果在后台代码设置了,响应对象(response)的
Content-Type 等于 application/json; charset=utf-8 时,
JQuery的 Ajax 请求可以不用有 dataType 属性。

结论:
  其实讨论了这么多就是解决 2.4 中要解决的问题,客户端如何
解析你返回的字符,就是通过 Content-Type 属性决定。
 这么多种方法为的是给让大家用着方便,少走弯路!(我是走了弯路
了,很不爽!)
  我喜欢用 2.4 的方法,个人喜好而已!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值