ASP.NET MVC: best way to return an AjaxRequest type?

I have several ActionResults in my controller. Almost all of them process either AjaxRequest or regular request-dependent requests (duh!). The fact is that if I add something to the database using AjaxRequest, I just want to return OK or ERROR (or 1 or 0, etc.) to my page instead of View () or ParcialView () because I I will process through ajax on the client, and I just need the answer “yes” or “no” (or any other main answer).

If I have a regular request (not ajax), this is normal, because I 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:);
 }
+3
3

:

return Content("ok");

JSON :

return Json(new { result = true });

UPDATE:

jQuery , JSON, success , :

$.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!'); 
    } 
});
+4

, ActionFilter, ajax.

0

. JQuery , 'dataType'. . ! .

 $.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!');
         }
       });
0

Source: https://habr.com/ru/post/1728668/


All Articles