views:

32

answers:

1

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.

How others handle such a case?

+2  A: 

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.

Darin Dimitrov