ASP.NET中MVC使用AJAX调用JsonResult方法并返回自定义错误信息

一、如何用AJAX调用JsonResult方法

比如FuckController中添加有个返回JsonResult类型的方法FuckJson():

代码如下:

<span class="kwd">public<span class="pln"> <span class="typ">JsonResult<span class="pln"> <span class="typ">FuckJson<span class="pun">()<span class="pln">
<span class="pun">{<span class="pln">
    <span class="kwd">return<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">JsonResult<span class="pun">()<span class="pln">
    <span class="pun">{<span class="pln">
        <span class="typ">Data<span class="pln"> <span class="pun">=<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">List<span class="str"><string><span class="pun">()<span class="pln"> <span class="pun">{<span class="pln"> <span class="str">"fuck"<span class="pun">,<span class="pln"> <span class="str">"shit"<span class="pln"> <span class="pun">},<span class="pln"> <span class="typ">JsonRequestBehavior<span class="pln"> <span class="pun">=<span class="pln"> <span class="typ">JsonRequestBehavior<span class="pun">.<span class="typ">AllowGet<span class="pln">
    <span class="pun">};<span class="pln">
<span class="pun">}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

如果我们直接在浏览器里调用,是可以看到结果的:

因为在浏览器地址栏直接输入这个地址,是一次GET请求,这就是为毛上面的代码里要写JsonRequestBehavior.AllowGet。

用JQuery AJAX调用的代码如下:

代码如下:

<span class="pln">$<span class="pun">.<span class="pln">ajax<span class="pun">({<span class="pln">
    url<span class="pun">:<span class="pln"> <span class="str">"/Fuck/FuckJson"<span class="pun">,<span class="pln">
    data<span class="pun">:<span class="pln"> <span class="str">""<span class="pun">,<span class="pln">
    dataType<span class="pun">:<span class="pln"> <span class="str">"json"<span class="pun">,<span class="pln">
    type<span class="pun">:<span class="pln"> <span class="str">"POST"<span class="pun">,<span class="pln">
    contentType<span class="pun">:<span class="pln"> <span class="str">"application/json; charset=utf-8"<span class="pun">,<span class="pln">
    dataFilter<span class="pun">:<span class="pln"> <span class="kwd">function<span class="pln"> <span class="pun">(<span class="pln">data<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
        <span class="kwd">return<span class="pln"> data<span class="pun">;<span class="pln">
    <span class="pun">},<span class="pln">
    success<span class="pun">:<span class="pln"> <span class="kwd">function<span class="pln"> <span class="pun">(<span class="pln">data<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
        alert<span class="pun">(<span class="pln">data<span class="pun">);<span class="pln">
    <span class="pun">}<span class="pln">
<span class="pun">})</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

url: "/Fuck/FuckJson" 很显然是Action的位置。data: "" 表示FuckJson()放方没有参数。dataType: "json"是理所当然的,我们返回的就是JsonResult。

二、返回自定义错误消息

默认情况下,如果AJAX请求发生了错误。它最多只知道错误码,而无法显示具体的错误信息。但报错通常是需要的,所以我们先要写一个过滤器,作用是一旦发生exception,就给返回的json中的data属性加一个errorMessage。并且,response的状态不能是200,不然ajax请求会以为没有发生错误。一般的服务器端错误代码是500。这个过滤器函数如下:

代码如下:

<span class="kwd">public<span class="pln"> <span class="kwd">class<span class="pln"> <span class="typ">JsonExceptionFilterAttribute<span class="pln"> <span class="pun">:<span class="pln"> <span class="typ">FilterAttribute<span class="pun">,<span class="pln"> <span class="typ">IExceptionFilter<span class="pln">
<span class="pun">{<span class="pln">
    <span class="kwd">public<span class="pln"> <span class="kwd">void<span class="pln"> <span class="typ">OnException<span class="pun">(<span class="typ">ExceptionContext<span class="pln"> filterContext<span class="pun">)<span class="pln">
    <span class="pun">{<span class="pln">
        <span class="kwd">if<span class="pln"> <span class="pun">(<span class="pln">filterContext<span class="pun">.<span class="typ">RequestContext<span class="pun">.<span class="typ">HttpContext<span class="pun">.<span class="typ">Request<span class="pun">.<span class="typ">IsAjaxRequest<span class="pun">())<span class="pln">
        <span class="pun">{<span class="pln">
            filterContext<span class="pun">.<span class="typ">HttpContext<span class="pun">.<span class="typ">Response<span class="pun">.<span class="typ">StatusCode<span class="pln"> <span class="pun">=<span class="pln"> <span class="lit">500<span class="pun">;<span class="pln">
            filterContext<span class="pun">.<span class="typ">ExceptionHandled<span class="pln"> <span class="pun">=<span class="pln"> <span class="kwd">true<span class="pun">;<span class="pln">
            filterContext<span class="pun">.<span class="typ">Result<span class="pln"> <span class="pun">=<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">JsonResult<span class="pln">
            <span class="pun">{<span class="pln">
                <span class="typ">Data<span class="pln"> <span class="pun">=<span class="pln"> <span class="kwd">new<span class="pln">
                <span class="pun">{<span class="pln">
                    errorMessage <span class="pun">=<span class="pln"> filterContext<span class="pun">.<span class="typ">Exception<span class="pun">.<span class="typ">Message<span class="pln">
                <span class="pun">},<span class="pln">
                <span class="typ">JsonRequestBehavior<span class="pln"> <span class="pun">=<span class="pln"> <span class="typ">JsonRequestBehavior<span class="pun">.<span class="typ">AllowGet<span class="pln">
            <span class="pun">};<span class="pln">
        <span class="pun">}<span class="pln">
 
    <span class="pun">}<span class="pln">
<span class="pun">}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

之后,我们要给FuckJson()方法加上这个“特征”(Attribute在C#中最好不要翻译为属性),然后故意抛个错做测试。修改后的方法如下:

代码如下:

<span class="pun">[<span class="typ">JsonExceptionFilterAttribute<span class="pun">]<span class="pln">
<span class="kwd">public<span class="pln"> <span class="typ">JsonResult<span class="pln"> <span class="typ">FuckJson<span class="pun">()<span class="pln">
<span class="pun">{<span class="pln">
    <span class="kwd">try<span class="pln">
    <span class="pun">{<span class="pln">
        <span class="kwd">throw<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">Exception<span class="pun">(<span class="str">"oh shit!"<span class="pun">);<span class="pln">
        <span class="kwd">return<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">JsonResult<span class="pun">()<span class="pln">
        <span class="pun">{<span class="pln">
            <span class="typ">Data<span class="pln"> <span class="pun">=<span class="pln"> <span class="kwd">new<span class="pln"> <span class="typ">List<span class="str"><string><span class="pun">()<span class="pln"> <span class="pun">{<span class="pln"> <span class="str">"fuck"<span class="pun">,<span class="pln"> <span class="str">"shit"<span class="pln"> <span class="pun">},<span class="pln"> <span class="typ">JsonRequestBehavior<span class="pln"> <span class="pun">=<span class="pln"> <span class="typ">JsonRequestBehavior<span class="pun">.<span class="typ">AllowGet<span class="pln">
        <span class="pun">};<span class="pln">
    <span class="pun">}<span class="pln">
    <span class="kwd">catch<span class="pln"> <span class="pun">(<span class="typ">Exception<span class="pln"> ex<span class="pun">)<span class="pln">
    <span class="pun">{<span class="pln">
        <span class="kwd">throw<span class="pln"> ex<span class="pun">;<span class="pln">
    <span class="pun">}<span class="pln">
<span class="pun">}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

捕获异常后,你也可以先记一下log、或是根据你自己的需要处理一下这个异常,然后再throw。

最后我们的AJAX请求代码也得做修改,增加一个error的处理:

代码如下:

<span class="pln">$<span class="pun">.<span class="pln">ajax<span class="pun">({<span class="pln">
    url<span class="pun">:<span class="pln"> <span class="str">"/Fuck/FuckJson"<span class="pun">,<span class="pln">
    data<span class="pun">:<span class="pln"> <span class="str">""<span class="pun">,<span class="pln">
    dataType<span class="pun">:<span class="pln"> <span class="str">"json"<span class="pun">,<span class="pln">
    type<span class="pun">:<span class="pln"> <span class="str">"POST"<span class="pun">,<span class="pln">
    contentType<span class="pun">:<span class="pln"> <span class="str">"application/json; charset=utf-8"<span class="pun">,<span class="pln">
    dataFilter<span class="pun">:<span class="pln"> <span class="kwd">function<span class="pln"> <span class="pun">(<span class="pln">data<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
        <span class="kwd">return<span class="pln"> data<span class="pun">;<span class="pln">
    <span class="pun">},<span class="pln">
    success<span class="pun">:<span class="pln"> <span class="kwd">function<span class="pln"> <span class="pun">(<span class="pln">data<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
        alert<span class="pun">(<span class="pln">data<span class="pun">);<span class="pln">
    <span class="pun">},<span class="pln">
    error<span class="pun">:<span class="pln"> <span class="kwd">function<span class="pln"> <span class="pun">(<span class="pln">fuckedObject<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
        <span class="kwd">try<span class="pln"> <span class="pun">{<span class="pln">
            <span class="kwd">var<span class="pln"> json <span class="pun">=<span class="pln"> $<span class="pun">.<span class="pln">parseJSON<span class="pun">(<span class="pln">fuckedObject<span class="pun">.<span class="pln">responseText<span class="pun">);<span class="pln">
            alert<span class="pun">(<span class="pln">json<span class="pun">.<span class="pln">errorMessage<span class="pun">);<span class="pln">
        <span class="pun">}<span class="pln"> <span class="kwd">catch<span class="pun">(<span class="pln">e<span class="pun">)<span class="pln"> <span class="pun">{<span class="pln">
            alert<span class="pun">(<span class="str">'something bad happened'<span class="pun">);<span class="pln">
        <span class="pun">}<span class="pln">
    <span class="pun">}<span class="pln">
<span class="pun">})</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

现在请求这个Action,会发现Response的状态已经是500了。并且返回了Json格式的错误信息。

(0)

相关推荐

  • js实现将json数组显示前台table中

    在最近的学习中遇到一个小问题,如何把JSON数组显示在前台的table中,经过一番借鉴和学习之后终于解决了这个问题.具体的代码如下: (前提:利用ajax获取过来的JSON字符串必须是规范的,这样才能解析正确.后台获取数据库中数据的代码省略了) 1.前台JS代码(使用之前引入JQuery的js库文件) $.ajax({ type: "GET", url: "UserList.ashx?Action=List",//利用ajax请求后台的并返回值 // data: &

  • 浅谈C#.NET、JavaScript和JSON

    写在前面 全部手打,没有多余的话,全部干货,基本上用到的我就记录了. 一.什么是JSON JSON:JavaScript Object Notation,是一种轻量级的数据交互格式,主要用于数据传输. 二.JSON语法规则 1.数据由键值对(映射)关系表示,使用 ":" 表示:   例子:"name" : "赵大". 2.数据之间使用 "," 分隔: 例子:"name" : "赵大",

  • 微信小程序通过api接口将json数据展现到小程序示例

    实现知乎客户端的一个重要知识前提就是,要知道怎么通过知乎新闻的接口,来把数据展示到微信小程序端上. 那么我们这一就先学习一下,如何将接口获取到的数据展示到微信小程序上. 1.用到的知识点 <1> wx.request 请求接口资源(微信小程序api中的发起请求部分) <2>swiper 实现轮播图的组件 <3>wx:for 循环语句 <4>微信小程序的基础知识 2.实现原理 首先,先看一下这个请求函数 wx.request({ url: '******',

  • 简单谈谈MySQL5.7 JSON格式检索

    MySQL5.7版本开始支持JSON格式,在创建表时,可以指定列表的数据类型为JSON,但是如何在JSON格式上创建索引呢?? 本人做了一个简单测试. 第一步:建立一个包含JSON类型的表: CREATE TABLE json_test` ( id` int (8) NOT NULL AUTO_INCREMENT, content` json NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 第二步:初始化数据

  • Asp.net配合easyui实现返回json数据实例

    本文实例讲述了Asp.net配合easyui实现返回json数据的实现方法.分享给大家供大家参考.具体如下: 最近想用asp.net配合easyui开发一个小框架,然后再用到easyui的combobox的时候出现了一个问题,总所周知,easyui的文档上给出的combobox的格式是 复制代码 代码如下: <input class="easyui-combobox"               name="language"              dat

  • Bootstrap 填充Json数据的实例代码

    本文介绍Bootstrap 填充Json数据,具体如下: 一.如图: 二.html代码: <%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <div class="content"> <div class="table-responsive"> &l

  • .Net基于MVC4 Web Api输出Json格式实例

    本文实例讲述了.Net基于MVC4 Web Api输出Json格式的方法,分享给大家供大家参考.具体实现方法如下: 1.Global 中增加json输出 复制代码 代码如下: GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"

  • js遍历json的key和value的实例

    原生js遍历json对象 遍历json对象: 无规律: <script> var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}]; for(var i=0,l=json.length;i<l;i++){ for(var key in json[i]){ alert(key+':'+json[i][key]); } } </script> 有规律: packJson = [ {"name":&q

  • ASP.NET中实现把Json数据转换为ADO.NET DataSet对象

    Json数据转换为ADO.NET DataSet其实方法有很多,Newtonsoft.Json也提供了DataSet的Converter用以转换Json数据.但是有些情况下DataSet Converter并不管用,而且也不一定能够满足项目需要.这里介绍另一种简单有效的方法,能够方便快速地将Json数据转为ADO.NET DataSet. 设计 事实上Newtonsoft.Json已经提供了一套完整的Json数据文档结构,Newtonsoft.Json.Linq命名空间下提供了这种文档结构的对象

  • JSON在ASP.NET中使用方法

    Json.NET的简单介绍 首先介绍一个为方便在.NET中使用JSON的API,Json.NET.它方便我们读取从浏览器流向服务器的JSON对象,也方便在响应流中写入JSON对象. Json.NET只提供了服务器端的方法,主要有实现JSON文本与XML互相转换的类,有自定义读写JSON的JsonReader类和JsonWriter类,还有一个非自定义读写JSON的JavaScriptSerializer类. ASP.NET AJAX中,服务器端由JavaScriptSerializer类的几个方

随机推荐