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

一、如何用AJAX调用JsonResult方法

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

复制代码 代码如下:


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

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

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

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

用JQuery AJAX调用的代码如下:

复制代码 代码如下:


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

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

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

二、返回自定义错误消息

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

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzgdw.html