views:

59

answers:

3

I have Multiple ActionResults in my Controller. Almost all of them process either AjaxRequest and normal requests, dependending on the request (duh!). The point is, if I'm adding something to the database using an AjaxRequest, I just want to return a OK or ERROR (or 1 or 0, etc..) to my page instead of a View() or a ParcialView() because I will handle via ajax on the client and I just need a yes or no response (or any other basic response).

If I have a normal request (not ajax), it's fine because I'll either redirect to another controller or return a simple View().

So the question is: what is the best way to return a simple value to my view when processing AjaxRequest()??

// logic to insert into the db (just an example)
result = Person.Add();

if(Request.IsAjaxRequest()) {

   if(result == ok)
      return true;
   else
      return false;
 }
 // Normal Request
 else {

   if(result == ok)
      return Redirect("PersonList");
   else
      return View("Error:);
 }
+4  A: 

To return plain text to the view:

return Content("ok");

Or use JSON alternatively:

return Json(new { result = true });

UPDATE:

jQuery will automatically detect that the server is sending JSON response and it will pass to the success callback an object that will contain the serialized properties:

$.ajax({ 
    type: "POST", 
    data: theForm.serialize(), 
    url: theForm.attr('action'), 
    success: function(json) { 
        alert(json.result); // result is the property name used in the controller
    },
    error: function() { 
        alert('Error!'); 
    } 
});
Darin Dimitrov
Thanks for that! And how could I handle the Jason response on my jquery ajax request? $.ajax({ type: "POST", data: theForm.serialize(), url: theForm.attr("action"), success: function(html OR jason) { , ??? erro: function() { alert('Error!'); } });
Guillermo Guerini
Great!! So I can have multiple serialized properties!! Thank you very much Darin!
Guillermo Guerini
Hey Darin, I'm getting an undefined error when I try to alert(jason.myPropertyName); my return is: return Jason(new {emptyField="msg", returnCode = 0}); Is that correct? Thanks again.
Guillermo Guerini
A: 

If this is standard behavior in your entire application, you might want to look into creating an ActionFilter that encapsulates your ajax logic.

Khalid Abuhakmeh
A: 

I found the problem. JQuery doesn't detect automatically the return type, so you need to specify using the 'dataType' property. Look at the code below. It worked perfectly! Thanks you all.

 $.ajax({
         type: "POST",
         data: theForm.serialize(),
         url: theForm.attr("action"),
         dataType: "json", // Choose the return type - json
         success: function(json) {
              alert(json.returnCode);
         },
         error: function() {
              alert('Error!');
         }
       });
Guillermo Guerini