MVC JSON动作返回bool

mar*_*are 8 asp.net asp.net-mvc jquery json

我的ASP.NET MVC操作编写如下:

    //
    // 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
    }
Run Code Online (Sandbox Code Playgroud)

我遇到了这个问题,因为在jquery函数中使用它时我遇到了各种错误,主要是toLowerCase()函数失败.

所以我不得不改变行为,他们将bool作为字符串返回bool(调用ToString()bool值),以便返回truefalse(在qoutes中)但我有点不喜欢它.

其他人如何处理这种情况?

Dar*_*rov 16

我会使用匿名对象(请记住,JSON是一个键/值对):

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
    );
}
Run Code Online (Sandbox Code Playgroud)

然后:

success: function(result) {
    if (result.isCalculateTax) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

备注:如果selected.calculateTax属性是布尔值,那么.NET命名约定就是调用它IsCalculateTax.