MVC JSON操作返回布尔值

8

我的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
    }

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

所以,我不得不改变操作方式,以便它们返回bool作为字符串(在bool值上调用ToString()),这样它们就会返回truefalse(在引号内),但我有点不喜欢这种方式。

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

1个回答

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
    );
}

然后:

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

备注:如果selected.calculateTax属性是布尔值,那么.NET的命名规范应该称其为IsCalculateTax


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接