ASP. NET MVC Ajax calls the Jsonresult method and returns a custom error message

Source: Internet
Author: User
Tags httpcontext

First, how to call the Jsonresult method with Ajax

For example, add a method that returns the Jsonresult type in Fuckcontroller Fuckjson ():

Public Jsonresult Fuckjson(){ Return New jsonresult ()  { data = newlist<string> ()   {  ,   }, jsonrequestbehavior = jsonrequestbehavior. Allowget };               /span>                

If we call it directly in the browser, we can see the result:

Because this address is entered directly in the address bar of the browser, it is a GET request, which is to write jsonrequestbehavior.allowget in the code above the hairs.

The code for calling with jquery Ajax is as follows:

$.Ajax({Url: "/fuck/fuckjson",Data: "",DataType: "JSON",Type: "POST",ContentType: "Application/json; Charset=utf-8 ", Datafilter: function   (data  return Data; }, Success: function  (data {< Span class= "PLN" > Alert (data}})          /span>                

URL: "/fuck/fuckjson" is clearly the location of the action. Data: "" indicates that Fuckjson () has no parameters. DataType: "JSON" is a matter of course, we return is Jsonresult.

Ii. Returning custom error messages

By default, if an AJAX request has an error. It knows only the error code and cannot display the specific error message. But the error is usually required, so we first write a filter, the effect is that once exception occurs, the Data property in the returned JSON is added to a errormessage. Also, the response state cannot be 200, otherwise the AJAX request will assume that no error has occurred. The typical server-side error code is 500. This filter function is as follows:

Public Class Jsonexceptionfilterattribute : FilterAttribute, Iexceptionfilter{ Public void Onexception(ExceptioncontextFiltercontext) { If (Filtercontext.RequestContext.HttpContext.Request.Isajaxrequest()) {Filtercontext.HttpContext.Response.StatusCode = 500;Filtercontext.Exceptionhandled = True;Filtercontext.Result = New Jsonresult { data  = new { errormessage Span class= "pun" >= Filtercontext. Exception. Message }, jsonrequestbehavior  = jsonrequestbehaviorallowget };} }}    /span>                

After that, we want to add this "feature" to the Fuckjson () method (attribute is best not translated as a property in C #), and then deliberately throw a wrong test. The modified method is as follows:

[Jsonexceptionfilterattribute]Public Jsonresult Fuckjson(){ Try { Throw New Exception("Oh shit!"); Return New Jsonresult() { Data = New List<string>() {  ,   }, jsonrequestbehavior =< Span class= "PLN" > jsonrequestbehavior. Allowget };} catch  ( Exception Ex)  { throw Ex;}}          /span>                

After catching an exception, you can also remember log, or handle the exception according to your own needs, and then throw.

Finally, our Ajax request code has to be modified to add an error handling:

$.Ajax({Url: "/fuck/fuckjson",Data: "",DataType: "JSON",Type: "POST",ContentType: "Application/json; Charset=utf-8 ",Datafilter: function (Data) { ReturnData; },Success: function (Data) {Alert(Data); },Error: function (Fuckedobject) { Try { Var json = $. (fuckedobject. Responsetext Alert (json. Errormessage } catch ( E  { Alert (  ' something bad happened ' );  } }})  /span>                  

Now request this action, you will find that the state of response is already 500. and returns a JSON-formatted error message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.