Best way to do an Action that does not return data

Asked

Viewed 297 times

7

I am making an ajax call to change an object. The call does not need to return anything. Only http 200 (OK) or 500 (error) code. I’m using the following code in the action but I don’t know if it’s the best:

return new EmptyResult();

What is the best way to do an Action that does not return data?

2 answers

5


Is using ActionResult same. The problem is that EmptyResult returns nothing even, or requisition code:

public ActionResult MinhaActionSucesso()
{    
   // Antes do MVC5
   return new HttpStatusCodeResult(200);

   // MVC5+
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

public ActionResult MinhaActionErroInterno()
{    
   // Antes do MVC5
   return new HttpStatusCodeResult(500);

   // MVC5+
   return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}

See more about the enumerations HttpStatusCode here.

See more about the HttpStatusCodeResult here.

3

For ASP.NET MVC the EmptyResult works well. But if the function of your action is only to be called by AJAX (i.e., basically an API), then you can also use an Apicontroller (ASP.NET Web API), and in its action you return this.Ok() or this.InternalServerError() (the type of return of the method would be IHttpActionResult), making its intention clearer:

public class TestController : ApiController
{
    public IHttpActionResult Get()
    {
        if (algumaCondicaoBoa)
        {
            return this.Ok();
        }
        else
        {
            return this.InternalServerError();
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.