How to transfer data from MVC to jQuery.ajax

We have an ASP.NET MVC project in which we use jQuery.ajax to send some form data to the controller. In some cases, the controller method is called my throwing in exceptions due to a bad SQL statement. I would like to handle the exception in TRY CATCH and pass in details of why the SQL query was hacked. Since I am handling the exception, the jQuery.ajax post gets HTTP 200 back from the server, so no errors occur. If I use the jQuery.ajax complete property, it seems that I can look for the details of the exception and show the user, but I'm not sure how I can do this from the controller side. At first I tried something like this on the controller side:

Public Function IndexPost(formvalues as FormCollection) as ActionResult Try ... Catch ex as Exception Dim sErr as String = "Exception occurred: " & ex.ToString ViewData("PostResult") = sErr End Try Return View() End Function 

And then added this to my jQuery.ajax post:

 complete: function (data) { var postDataResult = "<%=ViewData("PostResult")%>"; if (postDataResult.length>2) { alert("Value of post result: " + postDataResult); } } 

ViewData ("PostResult") is null, of course, due to ajax call.

Any ideas how I can pass the result back to an ajax call from my controller?

Tks

+4
source share
2 answers

Create a wrapper class around your answer from action methods and it will have the IsSuccess property. In your jQuery success method, check the value of the IsSuccess property and follow the appropriate steps.

Let me create a common wrapper that can be used for all of your viewmodels / response objects.

 public class ApiResponse<T> { public bool IsSuccess { set; get; } public string ErrorCode { set; get; } public string Message { set; get; } public T Data { set; get; } } 

Now in your action methods

 public ActionResult Save(CustomerVM model) { var response=new ApiResponse<Customer>() { Data= new Customer() }; try { //Everythiing went good. response.IsSuccess=true; } catch(Exception ex) { response.Message="Failed to save"; } return Json(response,JsonRequestBehaviour.AllowGet); } 

Client side

 $.post("Save",{ "name" :"SSS"},function(r){ if(r.IsSuccess) { //Do something } else { //Error occured, alert(r.Message); } }); 
+2
source

You can use the "Json ()" method, which is a method of the "Controller" class, to return a json object in your ajax post. The Json method expects an object to be the json object received by your ajax call.

I do not know the syntax of VB, but it should look like this:

 catch ex as Exception Dim sErr as String = "Exception occurred: " & ex.ToString Dim jsonObject= New With { .success = False, .errorMessage = sErr} Return Json(jsonObject, JsonRequestBehavior.AllowGet) End Try 

Then in javascript you can read it like this:

 complete: function (data) { if(!data.success) { alert("Error message: " + data.errorMessage); } } 
+1
source

All Articles