Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC JSON actions returning bool

I had my ASP.NET MVC actions written like this:

    //
    // GET: /TaxStatements/CalculateTax/{prettyId}
    public ActionResult CalculateTax(int prettyId)
    {
        if (prettyId == 0)
            return Json(true, JsonRequestBehavior.AllowGet);

        TaxStatement selected = _repository.Load(prettyId);
        return Json(selected.calculateTax, JsonRequestBehavior.AllowGet); // calculateTax is of type bool
    }

I had problems with this because when using it in jquery functions I had all sorts of error, mostly toLowerCase() function failing.

So I had to change the actions in a way that they return bool as string (calling ToString() on bool values), so that thay return true or false (in the qoutes) but I kinda don't like it.

How do others handle such a case?

like image 885
mare Avatar asked Sep 20 '10 18:09

mare


People also ask

What is return JSON in MVC?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

What is IAction result?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result. RedirectResult - Represents a redirection to a new URL.

Which class will you use for sending the result back in Json format in MVC?

For sending back the result in JSON format in any MVC application, you have to implement the “JSONRESULT” class in your application.


1 Answers

I would use anonymous object (remember that JSON is a key/value pairs):

public ActionResult CalculateTax(int prettyId)
{
    if (prettyId == 0)
    {
        return Json(
            new { isCalculateTax = true }, 
            JsonRequestBehavior.AllowGet
        );
    }

    var selected = _repository.Load(prettyId);
    return Json(
        new { isCalculateTax = selected.calculateTax }, 
        JsonRequestBehavior.AllowGet
    );
}

And then:

success: function(result) {
    if (result.isCalculateTax) {
        ...
    }
}

Remark: if the selected.calculateTax property is boolean the .NET naming convention would be to call it IsCalculateTax.

like image 163
Darin Dimitrov Avatar answered Oct 05 '22 04:10

Darin Dimitrov